Перейти к содержимому
Madiyar92

Мадияр Айтбаев

@Madiyar92

На сайте с 24 декабря 2010 г.Казахстан, Талды-Курган

Пользователь пока ничего не рассказал о себе.

рейтинг

100

постов

7

комменты

5

подписчика

3

подписки

3

Area of Triangles

Let's learn about the area of Triangle. Let's start with the basics.

1. Right triangle and Triangle with a height.

Area of both triangles equals: A = h * c / 2

Let's prove for the second triangle (the first one can be proved similarly):

Area(ADC) = h*(d+c)/2, which is half area of rectangle with sides d+c and h

Area(ADB) = h*d/2, which is half area of rectangle with sides d and h

Area(ABC) = Area(ADC) - Area(ADB) = h*(d+c)/2 - h*d/2 = h*c/2

Thus, Area(ABC) = h*c/2

2. Triangle with two sides and angle

A = b*c*sin(A)/2

Let's prove it:

Draw a height,

A = b * c * sin(A)/2

sin(A) = opposite/hypotenuse = h / b

thus,

A = b * c * (h/b) /2

which  can be simplified to:

A = c * h / 2 and this formula we've proved above.

The End.

 
1
0
357

Quadratic Equation: a*x^2+b*x+c = 0

We all know about quadratic equation. We had solved it many many times in school. Let's recall about quadratic equation.

Quadratic Equation is a second-order polynomial equation in a single variable:

Solutions for x is:

x1 =(-b + sqrt(b^2-4*a*c))/(2*a)

x2 =(-b - sqrt(b^2-4*a*c))/(2*a)

 

What if we've forgotten the formula ? Let's try to reinvent this formula by ourselves.

1. Subtract left and right part of the equation by c. We will get:

2. Divide both parts by a.

3. (x+y)^2 = x^2 + 2*x*y + y^2. Let's try to transform left part to (x+y)^2.

To be able to do that, add b/(2*a) to both parts of the equation:

4. Open the brackets.

 

5. Simplify left part to a form (x+y)^2, and make denominators of the right part of the equation the same.

6. Right part can be simplified to:


7. Take the square root of both part:

Why +-sqrt(b^2-4*a*c) ? because (-3)^2 = 9 and 3^2 = 9, that's why :).

 

8. Subtract b/(2*a) from both parts:

9. The final answer is:

The End.

1
0
458

Pythagorean theorem: a^2+b^2=c^2

tl;dr; If you aren't eager to learn proof of the pythagorean theorem, you can stop reading.

I hope, almost everybody knows or has heard about pythagorean theorem. I am not aware in which year of school it is taught, but it is definitely in school syllabus. In this post, I am going to write proof of it.

Let's recall pythagorean theorem. If we have right triangle(triangle with a 90-degree angle) ABC , then this equation is true:

a^2 + b^2 = c^2

or in other denotations:

|BC|^2 + |AC|^2 = |AB|^2


1. Proof by area

We want to proof that a^2+b^2=c^2.

Area of the outside rectangle is equal to (a+b)^2. But, there is a other way to calculate outside area, we can sum up area of the inside rectangle and four right triangles, which are located on the corners.

(a+b)^2 = c^2 + (a*b)/2 * 4

if we open the bracket on the left side,

a^2+2*a*b+b^2=c^2+2*a*b

subtract 2*a*b from both sides,

a^2+b^2=c^2

End of the proof


2. Proof by triangle

Try to come up, why angle at Point C is divided into b and a ? (btw, it is called similar triangles).

sin(a) = opposite/hypotenuse = |BC| / |AB| = |BD| / |BC|

cos(a) = adjacent/hypotenuse = |AC| / |AB| = |AD| / |AC|

in other words,

|BC|^2 = |AB| * |BD| - derived by cross multiplying the sin(a) proportion above.

|AC|^2= |AB| * |AD| - derived by cross multiplying the cos(a) proportion above.

if we sum up two equations,

|BC|^2+|AC|^2=|AB|*(|AD|+|BD|)

From the picture we can verify that:

|AD|+|BD|=|AB|

Thus,

|BC|^2+|AC|^2=|AB|^2

End of the proof.


 
2
4
591

ProjectEuler 144: Investigating multiple reflections of a laser beam

tl;dr; you can stop reading, if you aren't interested in programming or math.

In this post, I want to show you importance of programming in math field. For a year I was afraid to solve one geometrical problem. So today decided to overcome my fear.

I don't want to make you afraid of this post. So let's start with something simple.

1. Draw an ellipse

We are given an ellipse with the equation: 4*x^2+y^2 = 100

So we want to visualise the ellipse. In the end, we want to plot ellipse as shown in the following picture:

There is a great python plotting library for that: matplotlib.

Firstly, notice that x needs to be between -5..5 inclusive, otherwise 4*x^2 + y^2 will be greater that 100.

If we know x, then y = sqrt(100-4*x^2) or y = -sqrt(100-4*x^2)

Let's take 5 points from [-5..5] and draw line between them.

import numpy as np
import matplotlib.pyplot as plt
import math

plt.figure(figsize=(4,5))

X = np.linspace(-5, 5, 5) 
Y = [math.sqrt(100-4*x*x) for x in X]
plt.plot(X, Y, color="red")
plt.show()

We will get something like that:

Have you noticed 5 points? Let's draw more points, let's say 100 points.

import numpy as np
import matplotlib.pyplot as plt
import math

plt.figure(figsize=(4,5))

X = np.linspace(-5, 5, 100) 
Y = [math.sqrt(100-4*x*x) for x in X]
plt.plot(X, Y, color="red")
plt.show()

Have you noticed which number has changed in the code?

Looks like we have drawn upper part of the desired ellipse, lower part can be drawn similarly:

import numpy as np
import matplotlib.pyplot as plt
import math

plt.figure(figsize=(4,5))

X = np.linspace(-5, 5, 100) 
Y = [math.sqrt(100-4*x*x) for x in X]
plt.plot(X, Y, color="red")
Y = [-math.sqrt(100-4*x*x) for x in X]
plt.plot(X, Y, color="blue") 
plt.show()

Let's try to draw a line between points (0, 10.1) and (1.4, -9.6):

import numpy as np
import matplotlib.pyplot as plt
import math

plt.figure(figsize=(4,5))

X = np.linspace(-5, 5, 100) 
Y = [math.sqrt(100-4*x*x) for x in X]
plt.plot(X, Y, color="red")
Y = [-math.sqrt(100-4*x*x) for x in X]
plt.plot(X, Y, color="blue") 
plt.plot([0, 1.4], [10.1, -9.6], color="black")
plt.show()

2. Problem Statement

Now it's time to solve the real problem. You can read the statement from here: ProjectEuler 144.

Shortly, you are given the equation of an ellipse: 4*x^2+y^2=100. The laser beam enters the ellipse at point (0, 10.1) and then touches point (1.4, -9.6), after that reflects, and so on... See the animation below or read the full statement:

3. Reflecting one segment

If we will learn to reflect the laser beam at one point, then we solved the problem, because after that we can just simulate it.

The picture above gives some draft ideas about how we are going to reflect the laser beam, i.e:

a. Find the normal vector(yellow segment) to tangent line(brown) at point q.

b. Find angle between laser beam and normal vector (i.e to find measure of the angle A). A is negative if laser beam is located in the left side of the normal vector.

c. Rotate the laser beam to 2*A angles, in other words rotate the point p around the point q to an angle 2*A.

d. Finally, find a point t (look to the picture), which will be located in the line formed by points q and rotated p.

3.a. Finding the normal vector

Let's recall lectures from calculus, specially gradient vector. Don't be afraid, it is just vector formed by partial derivatives at points x and y. In our case, gradient vector or normal vector will be (8*x, 2*y). I am not going to prove it, but I am going to use benefits of python to verify visually for correctness. Let's draw normal vector at random points.

Seems like something reasonable to continue.

3.b. Finding an angle between two vectors

From linear algebra we can remember that vector product of two vectors (x1, y1) and (x2, y2) is equal to x1*y2-y2*x1.

On the other hand, it equals  to  sqrt(x1^2+y1^2)*sqrt(x2^2+y2^2)*sin(A),

i.e

x1*y2-y2*x1=sqrt(x1^2+y1^2)*sqrt(x2^2+y2^2)*sin(A)

sin(A) = (x1*y2-y2*x1)/(sqrt(x1^2+y1^2)*sqrt(x2^2+y2^2))

A = arcsin((x1*y2-y2*x1)/(sqrt(x1^2+y1^2)*sqrt(x2^2+y2^2)))

def veclen(u):
    return (u[0] * u[0] + u[1] * u[1]) ** 0.5

def angle(u, v):
    dot = u[0] * v[1] - u[1] * v[0]
    sin = dot / veclen(u) / veclen(v)
    return math.asin(sin)
 

3.C. Rotation of a vector

You can read it from here. To be honest, I just copied the formula from wikipedia :D.

def rotate_vector(v, angle, origin):
    x, y = v
    x = x - origin[0]
    y = y - origin[1]
    cos_theta = math.cos(angle)
    sin_theta = math.sin(angle)
    nx = x*cos_theta - y*sin_theta
    ny = x*sin_theta + y*cos_theta
    nx = nx + origin[0]
    ny = ny + origin[1]
    return np.array([nx, ny])

After this step we will get this picture, now the last step is to find point t.

3.D Finding the point t.

Now we have points q and rotated p. We want to find point t, such that it belongs to a line formed by points (q, rotated p) and belongs to the ellipse.

One way to solve, is to parameterise the line equation. Lets denote rotated p as pr.

x=(pr.x-q.x) * k + q.x

y=(pr.y-q.y) * k + q.y

This is parametrised equation of the line formed by point points q and pr.

We want to find k, such that:

4*((pr.x-q.x) * k + q.x) ^ 2 + ((pr.y-q.y) * k + q.y) ^ 2 = 100

In a result, we can simplify it to a form a*k^2+b*k+c=0 and solve quadratic equation.

 

4. Final draw

First few reflections are drawn in the picture below, seems like the solution worked out.

You can find full code here: pastebin

By the way, we might draw nothing and solve the problem from projecteuler (it just needs a number). But by drawing, it is easier to see that you are in the right direction.

2
0
860

Go as a first language

In my previous post I described Go in a general view. In this post I am going to write, so far as possible in a practical view.

First of all, in my point of view, Go is a perfect language as a teaching language. If someone started to dive into programming world from a different background, it is very important their first impression about programming language they are going to learn.

Before knowing Go, I thought Python suits perfectly as a first learning language.
But now I am not sure, because spaces/tabs adding some meanings to the code may be very confusing.

1. A + B

package main

import "fmt"

func main() {
        var a, b int
        fmt.Scanf("%d%d", &a, &b)
        fmt.Print(a + b)
}

Isn't it looks like C/C++? By the way, in my opinion, C++ is not good as a first language, because C++ is difficult even for experienced C++ developers :).
I think, I know about %5 (if not less) from C++'s specifications. A lot of rules and old language, thus overcomplicated. If you try to search something simple in forums, you will find dozens of different answers. In a result, you won't feel learning progress.

2. If

package main

import "fmt"

func main() {
        var n int
        fmt.Scanf("%d", &n)
        if n%2 == 0 {
                fmt.Println("Number is even")
        } else {
                fmt.Println("Number is odd")
        }
}

Nothing special? Yes, but there are some parts I like here.

The "If" statement doesn't need to be surrounded by brackets "()". If you try to surround it, "Gofmt" tool will delete it for you on a save. Thanks to "Gofmt" tool, codes will look like the same, which is amazing for learners.

Unlike many other languages, you can't write a single statement without braces "{}", i.e the following code won't compile:

if n%2 == 0 
    fmt.Println("Number is even")
else 
    fmt.Println("Number is odd")

I like this strictness, because you don't have to learn about when to put braces and when not. In addition, in many language's style guides (e.g java style guide) recommend to put braces even when they are optional. Fortunately, "Go" has only one way :).

3. For and while

package main

import "fmt"

func main() {
        var n int
        sum := 0
        n = 10
        for i := 0; i < n; i++ {
                sum += i
        }
        fmt.Println(sum)
}

Try to guess, will this code compile?
If yes, what is the difference between ":=" and "=" ?

Go's syntax does not provide a while loop. Seriously, why we need while, when for can do the same?

for ;i < n; {
    sum += i
}

If you try to save, "Gofmt" transforms it to even simpler code:

for i < n {
    sum += i
}

while (true) looks like this:

for {
}

4. Function

package main

import "fmt"

func triple(x int, y int) (int, int, string) {
        return x * 2, y * 3, "third"
}
func main() {
        fmt.Println(triple(1, 2))
}

A Function can return any number of variables, which is awesome.

package main

import "fmt"

func triple(x, y int) (a int, b int, s string) {
        a = x * 2
        b = y * 3
        s = "third"
        return
}
func main() {
        fmt.Println(triple(1, 2))
}

The same code, but showing different features of a function. Concretely, variables in parameters can share a type, return values can be named.

5. Arrays and slices.
Nothing to say about arrays, it is similar to arrays in other languages, but slices are awesome. We can think "slice" as a dynamic array.

package main

import "fmt"

func main() {
        a := make([]int, 5)
        for i := 0; i < 5; i++ {
                a[i] = i * i
        }
        b := a[1:4]
        fmt.Println(b) // [1, 4, 9]

        a = append(a, 111)
        for i, v := range a {
                fmt.Println(i, v)
        }
}

Slice is kind of similar to Python's list but isn't flexible as Python's. "Range" iterates over a slice and returns index, value (one of them can be omitted as "_").

6. Defer

package main

import "fmt"

func main() {
        defer fmt.Print("world")
        fmt.Print("hello ")
}

The output is: "Hello world". Defer is used to call the function after performing the surrounding function. It is commonly used to perform cleanup, e.g:

package main

import (
        "fmt"
        "os"
)

func main() {
        f, err := os.Create("~/a.txt")
        defer f.Close()
        if err != nill {
            return
        }
        // Do some other stuff
}

Now you don't have to worry about closing file before every "return" operation, "defer" will take care about it for you.

To sum up, Go is very awesome language. I can come up with several areas where Golang can be used optimally. One of them is as a learning language for kids, students (Maybe still Python better?).

Which programming language do you like most?

4
0
499

Testing Golang

This post is just for myself. I am learning english, so in my opinion to learn something you need to practice a lot. Shortly, sometimes I am going to write posts in english here, forgive me for my bad english grammar :).

In the past, I wanted to change my life a little bit, so decided to learn new programming language :D. In a result, picked young language Go/Golang.

GoLang is very tiny language, even all language specifications can fit into one single page. Of course, I didn't mention about size of the single page :). Language Specification

What I like in Go:

1. Great tools, great decisions. Especially to compile&run, you just need to type "go run main.go". Also great tool "gofmt" - it formats everything for you, i.e adds tabs/spaces, etc... I think "gofmt" is useful for beginners, for one less responsibility to learn :) . I remember when I started learning programming, I didn't use tabs/spaces at all, but when I started to add tabs/space I understood how formatting is important. In my editor, Go formats a code every time on save (I am not sure whether it is by default or I did something to make it happen).

2. Static typed language that feels like scripting language. I like very much Python. But, on the other hand, at my work I see some difficulties with python if we were using Python instead of Java. It is refactoring. I think (I have't any experience with it) refactoring dynamic typed languages is nightmare. Compiler won't complain for you in the most cases.

So for big projects static typed languages makes more sense unless you have very good coverage of unit tests. If we come to Go, it took best of both worlds. It is statically typed but it feels like scripting language.

3. Very fast. As Go is static typed language and compiles into machine code, it should be very fast. I haven't such experiences with it, so haven't felt how much it is faster than others. But it should be fast as C++ language.

4. With less go more. Go is very small language. I spent 15-20 minutes to write my first program. I like when learning curve is very little, but can do many things with it. When I have many, many choices of ways to do one thing, it is headache for me. Fortunately, by using Go mostly you have only one way to do things.

5. Concurrency. Very well supported concurrency on a language level. It is very simple to write multithreading tasks. I think, this is the most attractive one for most developers.

With advantages it brings disadvantages, too. At first, Go seems like an ugly language.

If you are interested in examples of Go, in the next post I will write some example programs in Go. By the way, if you see any, please fix my grammar/spelling :D.

 
2
4
566

C++: Tricky codes

This are my collections of c++ codes which are very tricky.

Some of them I found by making mistakes, so recorded them to avoid making the same bug twice.

Try to guess the output just by reading, please don't use any compiler or IDE.

Do you know other tricky codes?

 
1: A - B
  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. int a = 020;
  5. short b = 2;
  6. cout << a - b << endl;
  7. return 0;
  8. }
 
2. Condition
  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. bool ok = true;
  5. // Try to guess with if condition \
  6. if (!ok && true)
  7. cout << "I am ok" << endl;
  8. return 0;
  9. }
 
3. Comparison
  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. unsigned a = 0;
  5. int b = 2;
  6. if (a + b >= -2)
  7. cout << a + b << ">=" << -2 << endl;
  8. else
  9. cout << a + b << "<" << -2 << endl;
  10. return 0;
  11. }
 
4. Binary operation
  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. int a = 0, b = 1;
  5. if (a&b==0) {
  6. cout << (a&b) << "=" << 0 << endl;
  7. } else {
  8. cout << (a&b) << "!=" << 0 << endl;
  9. }
  10. return 0;
  11. }
 
5. Float casting
  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. long long a = 1e18 + 1;
  5. cout << a << endl;
  6. return 0;
  7. }
 
6. String size
  1. #include <iostream>
  2. using namespace std;
  3. int main(){
  4. string s ="a";
  5. for(int i =0; i <= s.size()-2;++i)
  6. cout << s[i]<<" ";
  7. return0;
  8. }
 

Upd.

Answers:

1. Output: "14". Because 020 is in octal base, therefore 16 - 2 = 14

2. Output: "I am ok". When you use "\", it means that you split one long line to several lines.

So, for a compiler the code looks like this:

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. bool ok = true;
  5. // Try to guess with if condition if (!ok && true)
  6. cout << "I am ok" << endl;
  7. return 0;
  8. }

3. Output: "2<-2". The reason is: unsigned int + int = unsigned int,

i.e unsigned type has higher priority than int when it comes to casting.

Thus, a + b is unsigned.

  1. if(2>=-2)// i.e unsigned >= int

In a result compiler casts both parts to unsigned. As a consequence, the line turns into:

  1. if (2 >= 4294967294)

but wait, why 4294967294? Numbers are stored in binary form. Negative number are stored in what's called two's complement. The two's complement of an n-bit number x is 2^n-x.

Thus, 2^32 - 2 = 4294967294.

4. Output: "0!=0". Because "==" has higher priority. Advice : look into priority table or always put brackets.

5. Output: "1000000000000000000" instead of "1000000000000000001". Because of the representation of float.

6. Output: Runtime Error. Because, s.size() returns "size_t" type which is unsigned integer type. So, s.size() - 2 is unsigned, so it turns into a huge number. In a result, runtime error because it tries to access non-existing index.


3
3
710