Julien De Wisscher - 8 months ago 61

Java Question

I'm a bit annoyed with a method I wrote to approximate sine function in Java. Here it is, it's based on Taylor's series.

`static double PI = 3.14159265358979323846;`

static double eps = 0.0000000000000000001;

static void sin(double x) {

x = x % (2 * PI);

double term = 1.0;

double res = 0.0;

for (int i = 1; term > eps; i++) {

term = term * (x / i);

if (i % 4 == 1) res += term;

if (i % 4 == 3) res -= term;

}

System.out.println(sum);

}

For little values, I got very good approximation of sine, but for large values (e.g pow(10,22)), results seems very very wrong.

Here are the results :

`sin(pow(10,22)) // 0.8740280612007599`

Math.sin(pow(10,22)) // -0.8522008497671888

Does someone have an idea ? Thank you !

Best regards,

Answer

Be reassured that the Java `sin`

function will be off too.

You problem is that the Taylor expansion for `sin`

has a small radius of convergence and convergence is slow even if you're within that radius.

There are floating point considerations too: a floating point `double`

gives you about 15 significant figures of accuracy.

So for large arguments for `sin`

, the accuracy will deteriorate significantly especially given that `sin`

is a *periodic* function:

`sin(x + 2 * pi * n) = sin(x)`

for any integer `n`

.