0

When trying to get the cos of 90 using this code

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

This prints 6.123233995736766E-17 Why does this happen and what have i done wrong

Edit i solved this using a custom function(Where the amounts of zeros is how rounded the number becomes):

double round(double value){
  return((double)Math.round(value * 100000d) / 100000d);
}

Thanks too https://stackoverflow.com/users/20459/asterite for the function

Nixcc
  • 63
  • 7
  • 1
    Long story short, the value you are getting back _is_ technically zero, but there are some very small rounding errors, due to the way that floating point (inexact) arithmetic behaves inside a computer. If you need an _exact_ calculation, then look into using Java's `BigDecimal` class. – Tim Biegeleisen Aug 13 '20 at 10:06
  • @TimBiegeleisen how would you represent `pi/2` exactly with `BigDecimal`? – Andy Turner Aug 13 '20 at 10:20
  • You are concerned with a value that is out by less than 10 thousand trillionth of a unit yet you say you solved it by increasing the error (rounding) . Your solution has made every other value much less accurate, up to 100 billion times less accurate. You can not increase the precision by rounding, – Blindman67 Aug 14 '20 at 02:50

0 Answers0