Lysander77
Lysander77

Reputation: 21

Float and double precision in trigonometric functions

The IEEE 754 standard says that float (32 bit) use 23 bit for the mantissa, which permits to store all the digits of every reals up to roughly 10⁷. For trigonometric functions such as cos() or sin(), the least significant bits are important. Therefore one can expect the result of sin() and cos() of float variables to be wrong after 10⁷ as a part of mantissa is lost during encoding.

for (int i = 0; i <= 15; i++) {
    System.out.println("for 10^" + i);
    System.out.println(Math.sin((float) Math.pow(10, i)));
    System.out.println(Math.sin(Math.pow(10, i)));
}

This code shows that sin() and cos() of float variables stays exact up to 1010, which is a behavior I don't understand... How can the cos() and sin() process the exact value as the parameter itself lacks precision?

Upvotes: 2

Views: 515

Answers (1)

CMuirPrice
CMuirPrice

Reputation: 11

An IEEE float has 24 bits of precision in the mantissa (23 explicitly stored, plus 1 "hidden" bit). The key to the behavior you see is that when 1010 is written in binary it is 34 bits long, but the last 10 bits are all "0". Therefore, the single precision representation is exact for this particular number.

Upvotes: 1

Related Questions