Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 6980

Python • Python Floating point maths, correcting?

$
0
0
There have been a few times when I have attempted to write programs in Python which use a bit of maths and the results I have obtained were not as expected. Having read up about it a little it seems this behaviour is due to the way binary floating point arithmetic works, but that frankly does not satisfy me at all. I just want any maths calculations I do in Python to produce the correct / humanly expected results.

This very small bit of code illustrates the problem:

Code:

Num=24.680TimesThree=Num*3T3Div=(Num*3)/0.01print(Num, TimesThree, T3Div)
The output, when run, is

Code:

24.6874.039999999999997403.999999999999
The answers from the calculations in lines 2 and 3 obviously should be

Code:

74.04
and

Code:

7404
How can I force these Python calculations to give the correct results? I understand there's a library called 'Decimal' which is intended for this purpose, but I can't get my head around how to use it. Can anyone show me how to apply the 'Decimal' library to 'fix' the results of Python maths calculations, using the above calculations to illustrate its use?

Or, are there better tools for maths in Python? Numpy for example?

Statistics: Posted by SiriusHardware — Sat Jan 03, 2026 7:28 pm — Replies 2 — Views 27



Viewing all articles
Browse latest Browse all 6980

Trending Articles