How do calculators work with precision?

I wonder how calculators work with precision. For example, the value is sin(M_PI)not zero when calculated exactly double:

#include <math.h>
#include <stdio.h>

int main() {
    double x = sin(M_PI);
    printf("%.20f\n", x); // 0.00000000000000012246
    return 0;
}

Now, of course, I want to print zero when the user enters sin (π). I can easily get around somewhere on 1e-15 so that this particular case works, but it's a hack, not a solution. When I start spinning like this and the user enters something like 1e-20, they get a null result (due to rounding). The same thing happens when the user enters 1/10 and presses the key several times =- when he reaches rounding, he gets zero.

Still, some calculators return zero for sin (π), and at the same time, they can conveniently work with expressions (1e-20) / 10. Is there a trick?

+5
4

. , , . ( ) .

,

printf (%12.4d, number);
+4

.

:

  • BCD
  • , .
+3

, . , , , .

+2

The trick is probably, as already mentioned, that calculators will use arbitrary precision math libraries or lookup tables .

I would also add that your code snippet works this way due to the use of floating point arithmetic , which, as you probably know, math is incorrect in the sense that it is inaccurate - 1.0 + 0.1 != 1.1(it is actually 1.1000000000000001) :)

+2
source

All Articles