[758] in java-interest
Re: trig precision problems?
daemon@ATHENA.MIT.EDU (Jim Graham)
Tue Jul 18 21:35:00 1995
Date: Tue, 18 Jul 1995 16:08:16 -0700
From: flar@bendenweyr.Eng.Sun.COM (Jim Graham)
To: java-interest@java.Eng.Sun.COM, misfeldt@mda.ca
> In porting C++ programs to java, I came across a
> problem in the accuracy of the java trigonmetric
> functions. As an example, I use sin() here.
>
> double x = 0.5;
> double y = Math.sin( 0.5 );
> System.out.println( "y: " + y );
> double y2 = y - 0.4794;
> System.out.println( "y2: " + y2 );
>
> The above code fragment produces:
>
> y: 0.479426
> y2: 2.55297e-05
There must be something wrong with the calculation of "y - 0.4794". It
must have to do with the fact that 0.4794 is first represented as a
regular float when the compiler parses it and then it is later converted
to a double and the subtraction is only accurate to the precision of
a regular float.
I tried the following and it gave a much more accurate response:
double x = 0.5;
double y = Math.sin(0.5);
System.out.print("0.");
for (int i = 0; i < 5; i++) {
y *= 10000;
int y3 = (int) Math.floor(y);
System.out.print(y3);
y -= y3;
}
System.out.println();
produces:
0.47942553860420302953
...jim
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com