Draw square with polar coordinates

Joel picture Joel · Jan 25, 2011 · Viewed 10.6k times · Source

I have a square, where the closest points are 1 unit away from the center. See my ascii diagram below:

+-----------+
|           |
|  x        |
|-----+     |
|           |
|           |
+-----------+

Therefore, the distance from the origin to the corners is the sqrt(2). I need a function that returns the distance from the origin to a point on the square at any angle. For example, for an input of 0, the function would return 1. For an input of 45, the function would return the distance to a corner, the square root of 2. Then for 90, it would return 1 again.

In other words, when you graph the function with polar graphing, it will draw a square.

I believe that the function would be something like this:

f(x) = sqrt(tan(x)^2+1)

The only problem is that the function above will not graph the sides of the square. I need something that draws all 4 sides.

I know that there is a trigonometric function for something similar to this, but I will be using this function in javascript, so I will only be able to use the standard trigonometry functions.

Any help will be appreciated. Thanks in advance.

Answer

Mano Kovacs picture Mano Kovacs · Jan 25, 2011

This would be faster I guess:

function getLengthForDeg(phi){
    phi = ((phi+45)%90-45)/180*Math.PI;
    return 1/Math.cos(phi);
}