# Thread: Check between two values

1. ## Check between two values

Hi everyone,

My code works out the following equation (from the algorithm on this page: http://williams.best.vwh.net/sunrise...lgorithm.htm):

L = M + (1.916 * sin(M)) + (0.020 * sin(2 * M)) + 282.634

...the result of this equation has to be between 0 and 360, and the algorithm says that

"L potentially needs to be adjusted into the range [0,360) by adding/subtracting 360"

At the moment, I have the following code:

Code:
```L = M + (1.916 * sin(M)) + (0.020 * sin(2 * M)) + 282.634;
if (L < 0)
{
L = L + 360;
}
else if (L > 360)
{
L = L - 360;
}
else
{
L = L + 0;
}

//Rest of program.```
This aims to add 360 if L is negative, and to subtract 360 if it is greater than 360, which (unless the answer is -360 > L > 360), should put it between 0 and 360. However, I am getting different values from my program and my calculator when I do it myself, and I think I am right, so what is my program doing wrong? Does the code above work for putting the answer between 0 and 360?

The value of M in both the program and my calculation is 81.7209, and my program puts L at 4.43216, but I get 6.2566 (which I think is correct).

Thanks a lot!

2. Check out that sin uses degrees it is normally in radians.

This should change L to a value between 0 and 360; it may only works if L is an integer.
(might not work if L is less that -360)
L = (L+360) % 360

3. I took another look, and it is indeed in radians. Is there a way to make C++ work in degrees? The formula won't work, even if you convert the angles to radians because the constants are designed around degrees.

Thanks.

4. Converting degrees into radians is a simple equation. You can us that.

5. That simple equation is, instead of,

Code:
`sin(M)`
you write

Code:
`sin(M * PI / 180)`
Of course you'll need to define PI in the global area like so:

Code:
`const double PI = 3.14159265358979;`

6. The formulae won't work even if you do convert the angles to radians because the constants in the equations are designed for use with degrees.

I did find this though:

degmath header

I think that may work.

7. What you say does not make sense. sin returns [-1, 1], regardless if you use degrees or radians. Thus, so long as you convert your input to the equivalent in radians, it should work, because sin will return the same value.

8. Originally Posted by Elysia
What you say does not make sense. sin returns [-1, 1], regardless if you use degrees or radians. Thus, so long as you convert your input to the equivalent in radians, it should work, because sin will return the same value.
Seconded. Although one idea from that degmath header link (it's a forum thread) is that you could instead write an inline function that converts degrees to radians.

Code:
`inline double ToRadians(double theta) { return theta * 3.141592653589793238 / 180; }`

Popular pages Recent additions