wood burning stoves*
The moose likes Beginning Java and the fly likes Math cos wth Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Math cos wth" Watch "Math cos wth" New topic
Author

Math cos wth

Dajka Ferenc
Greenhorn

Joined: Mar 09, 2012
Posts: 6
Hey there
Why do i get :
3.5083546492674384E-15
6.123233995736766E-17
as output?
Tim Moores
Rancher

Joined: Sep 21, 2011
Posts: 2408
That's #20 in http://www.coderanch.com/how-to/java/JavaBeginnersFaq
Dajka Ferenc
Greenhorn

Joined: Mar 09, 2012
Posts: 6
no its not
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Dajka Ferenc wrote:no its not


No, it definitely is. toRadians() is giving you an approximation of pi / 2, but with some error in it for the reasons stated in the FAQ, and then Math.cos() is adding more error, for the same reasons.

That's why when doing floating point calculations, we need to take those errors into account. For example when comparing for equality, we don't test if x == y but rather if Math.abs(x - y)< epsilon.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4343
    
    8

"and other arithmetic inaccuracies"...yes it is. In particular, 90 degrees = PI/2 radians, and Java cannot hold the value exactly in a floating point value. So when you take the cosine you end up with something very close to zero, instead of exactly zero.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

And this line here makes no sense:



You're taking degrees, converting to radians, which is fine, getting the cosine, which is fine, but then doing a radian ⇒ degree conversion on the cosine. That last step is trying to convert a unitless scalar into an angular measure, and that's not valid.

You're going deg ⇒ rad ⇒ scalar ⇒ deg. You'd need to add a call to Math.acos() in there for it to make sense.
Dajka Ferenc
Greenhorn

Joined: Mar 09, 2012
Posts: 6
yeah really, i didn't see it, looks like i'm tired a bit. thank you very much
 
 
subject: Math cos wth
 
Similar Threads
which is valid ?Math.cos(56)or .......
tan(90) and sin(90)/cos(90)
did you know that cos(90) != 0
Trying to calculate lines over pi/4
How far am I from directly opposite the Ranch?