Question

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.

Was it helpful?

Solution

This would be faster I guess:

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

OTHER TIPS

Original post is tagged Javascript, but I needed this for typed languages (e.g. C) where you can't modulus a float.

MonoMano's answer is correct, but for anyone else coming here needing the same thing, here's MonoMano's answer modified for C / ObjC / Java / etc:

/** c.f. http://stackoverflow.com/a/4788992/153422
* M_PI_2 is a constant: "PI / 2"
* M_PI_4 is a constant: "PI / 4"
*/
double getSquarePolarRadiusForRad(double phi){
    double phiInPiBy4Range = phi;
    while( phiInPiBy4Range > M_PI_4 )
        phiInPiBy4Range -= M_PI_2;
    while( phiInPiBy4Range < - M_PI_4 )
        phiInPiBy4Range += M_PI_2;

    return 1/cos(phiInPiBy4Range);
}

I came up with an equation that can work with the TI calculators because of their theta step function in the window section of their polar graph function. I don't know if it helps you. I guess it can only work if you are able to configure the theta (or degree) step.

r = (((s*sqrt(2)) - 5)/4) sin(4(x - (pi/8)) + (((s*sqrt(2)) + s)/4)

where s is the length of the side of the desired square

Set the theta step to pi/4 in order to plot the main points needed to create the image of a square

Again, this works with TI Calculators.

I'm not familiar enough with Javascript, but in the format used in Wolfram Alpha, the formula for the radius from the angle is:

min(1/abs(cos(theta)),1/abs(sin(theta))))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top