z3on
z3on

Reputation: 411

Math.cos() gives wrong result

According to Wolfram Mathematica: cos(50) = 0.6427876096865394;

But this code in Java:

    System.out.println(Math.cos(50));

gives 0.9649660284921133.

What is wrong with java.lang.Math?

Upvotes: 40

Views: 49266

Answers (5)

Manu
Manu

Reputation: 819

For me...

System.out.println(Math.cos(50));
System.out.println(Math.cos(new Double(50)));
System.out.println(Math.cos(Math.toRadians(50)));
System.out.println(Math.cos(Math.toRadians(new Double(50))));

returns

0.9649660284921133
0.9649660284921133
0.6427876096865394
0.6427876096865394



http://www.wolframalpha.com/input/?i=cos%2850deg%29

cos(50deg) give same result as cos(50)... so Wolfram is degree by default.

Upvotes: -2

fbafelipe
fbafelipe

Reputation: 4952

Most Java trigonometric functions expects parameters to be in radians. You can use Math.toRadians() to convert:

System.out.println(Math.cos(Math.toRadians(50)));

Upvotes: 2

Keppil
Keppil

Reputation: 46219

Math.cos() uses radians, so to get your expected result you need to do

System.out.println(Math.cos(Math.toRadians(50)));

Upvotes: 13

Martin James
Martin James

Reputation: 24857

Degrees <> radians...........

Upvotes: 2

Dan D.
Dan D.

Reputation: 32391

Math.cos() expects the parameter to be in radians. This will return the result you need:

Math.cos(Math.toRadians(50));

Upvotes: 101

Related Questions