henrydavc
henrydavc

Reputation: 97

Trigonometric calculation not working

My calculations show 75 * Cos(90) as zero. However, I get -22.46325...

I can confirm that it is NOT in radians because the radians value is -33.6055...

Here is what I have:

private static double RadianToDegree(double angle)
{
    return angle * (180.0 / Math.PI);
}

static void Main(string[] args)
{
    Console.WriteLine((75 * Math.Cos(RadianToDegree(90))).ToString());
}

Why am I getting a value of -22.46325 instead of 0?

Upvotes: 0

Views: 232

Answers (5)

Wai Ha Lee
Wai Ha Lee

Reputation: 8805

Math.Cos expects inputs in radians, not degrees:

public static double Cos(double d)

Parameters

d

An angle, measured in radians.

You said

My calculations show 75 * Cos(90) as zero

so presumably you are working in degrees.

You therefore need to use

private static double DegreeToRadian(double angle)
{
    return angle / (180.0 / Math.PI);
}

instead of

private static double RadianToDegree(double angle)
{
    return angle * (180.0 / Math.PI);
}

to convert the angle into radians as Math.Cos expects.

See this link to an ideone.com snippet to confirm it.

The result is 4.59227382683391E-15 but since you're dealing with floating point numbers, the result of Math.Cos(x) will never be zero (see, e.g. this StackOverflow question).

Upvotes: 1

n0rd
n0rd

Reputation: 12610

Your RadianToDegree method given the argument of 90 returns value of 5156.62015617741. Which is passed to Math.Cos. Math.Cos expects the angle in radians as an argument. That 5156.62015617741 radians in degrees would be:

5156.62015617741 / PI * 180 = 295452.571501057 = 252.571501057

cos of 252.571501057 degrees is -0.299515394, times 75 in your code gives -22.463654606 that you see (plus-minus floating point error).

As others already mentioned, you got your transformation backwards.

Upvotes: 0

Richard Schwartz
Richard Schwartz

Reputation: 14628

You've got the conversion backwards:

private static double DegreesToRadians(double angle)
{

    return angle * (Math.PI / 180.0 );
}

static void Main(string[] args)
{
    Console.WriteLine((75 * Math.Cos(DegreeToRadians(90))).ToString());
}

Upvotes: 0

meklarian
meklarian

Reputation: 6625

You're passing in an argument to Math.Cos that your code suggests should be in degrees, while Math.Cos takes Radians.

See: https://msdn.microsoft.com/en-us/library/system.math.cos%28v=vs.110%29.aspx

Upvotes: 0

RadioSpace
RadioSpace

Reputation: 953

input is taken as radians so you need to convert degrees to radians

Upvotes: 2

Related Questions