4 ms·
> Math.sin(Math.PI/2) return 1.0 > Now, I don't get why this returns 1.0 and why not a number near to 1 but not exactly 1? ‘Accident’ of the implementation. Wh
by Someone 2y ago
> Math.sin(Math.PI/2) return 1.0
> Now, I don't get why this returns 1.0 and why not a number near to 1 but not exactly 1?
‘Accident’ of the implementation. When you feed Math.sin that IEEE float that’s close to π ÷ 2 it returns an approximation of its sine. In this case, the rounded result of 1.0, a result that you seem to think is an exact result.
> Same question here because Math.PI is not exact, why is its division so exact?
It’s not that computing Math.PI ÷ 6 is exact, but that then computing the sine of that value produces ½, which isn’t “so exact”, as technically, the bit pattern for Math.PI ÷ 6 doesn’t stand for π ÷ 6, and could have been computed in another way.
By the way, reading https://github.com/openjdk/jdk/blob/bd4160cea8b6b0fcf0507199ed76a12f5d0aaba9/src/java.base/share/classes/java/lang/Math.java#L39 https://github.com/openjdk/jdk/blob/bd4160cea8b6b0fcf0507199..., these results may vary between Java implementations, possibly even between runs (when a method gets called a lot, it may get optimized more, and start using a different implementation)
- shivajikobardan 2y agoYou the real MVP coz landed me into a goldmine. I was thinking this was due to difference in floating point multiplication and dvision algos.