In: Computer Science
in java Math.sin(Math.PI / 6) not being equal to 0.5 (but rather equals to 0.49999999999999994. Why is that?
Furthermore, if you try to print the following, you will notice that System.out.println(Math.sin(Math.PI/2)) gives you 1, but System.out.println(Math.cos(Math.PI/2)) does not give you 0, why are these two results not consistent?
Explantion:
This is a result of floating-point precision.
You can get certain number of significant digits. if anything that can't be represented exactly or if you get a approximated value you have to be rounded it to exact value to get a exact value of the result like sin or cos
For example, pi is not a rational number, and so it's impossible to get an exact representation. Since you can't get an exact value of pi, and you aren't going to get exact sin and cos of numbers including pi.
always use exact arithmetic numbers instead of approximate arithmetic value
Math.round(x) returns the value of x rounded to its nearest number
you can run the following java program to get System.out.println(Math.sin(Math.PI/2)) value 1 and System.out.println(Math.cos(Math.PI/2)) value 0
in the below program check the results of the values
// importing lang.Math functions
import java.lang.*;
class math
{
public static void main(String[] args)
{
// System.out.println("Round--Math.PI/6="+(Math.round(Math.PI/6)));
// System.out.println("Math.sin(Math.PI/6= "+(Math.sin(Math.round(Math.PI/6))));
// you have to take the mid value of 0.49999999999999994 to 0.8414709848078965 i.e 0.5
// here exact value is 0.5
System.out.println(" [after using Math.round] Math.sin(Math.PI/2= "+(Math.round(Math.sin(Math.round(Math.PI/2)))));
System.out.println("[after using Math.round] Math.cos(Math.PI/6= "+(Math.round((Math.cos(Math.round(Math.PI/2))))));
}
}
output Screen