[GiNaC-list] Unwanted digits when performing arithmetic computations
Richard B. Kreckel
kreckel at in.terlu.de
Sun Oct 27 00:11:07 CEST 2024
Hello,
On 10/26/24 5:38 PM, Dr. Mithun Bairagi wrote:
> Dear all ginac lovers, I have got some wrong results when performing
> some simple computations using ginac.
These results are not "wrong", see below.
> I have compiled and run the following c++ program using ginac-1.8.7,
> cln-1.3.7 (mingw64 compiler, gcc version 14.2.0, windows 10 os),
>
> #include <ginac/ginac.h>
>
> using namespace std;
> using namespace GiNaC;
>
> int main()
> {
> cout<<(numeric(0.1)+numeric(7))<<endl;
> cout<<(numeric("0.01")*numeric("9"))<<endl;
> cout<<(numeric("0.01")*numeric("99"))<<endl;
> }
>
> the above program shows the following result:
> 7.1000000000000000056
> 0.089999999999999999996
> 0.98999999999999999995
>
> I have got some unwanted digits which look very ugly. I think the result
> should be
> 7.1
> 0.09
> 0.99
This result is to be expected. Remember that CLN and GiNaC (and many
other systems) represent floating-point numbers in base 2, not in base 10.
In such systems, each floating-point number is an exact rational number
where the denominator happens to be a power of two.
An exact decimal fraction (such as 7.1 = 71/10 in decimal notation) can
be converted to an exact binary fraction if and only if the numerator is
a power of 2.
This is not the case for 71/10. On the other hand, it is the case for
e.g 75/10 = 15/2, so 7.5 can be converted from string "7.5" to an
internal representation exactly.
As an alternative, maybe you can use rational numbers such as 71/10
throughout your computations? Apart from that, there is no solution to
what you perceive as a "problem".
Mankind made a big mistake settling for base 10 millennia ago.
-richy.
More information about the GiNaC-list
mailing list