Pages

Showing posts with label Python - Utility - Float. Show all posts
Showing posts with label Python - Utility - Float. Show all posts

Thursday, July 25, 2024

Python : Utility : Float : Comparison in Floats

Comparing Floats in Python



Do not compare floats in Python using equality Operator.

As shown in the example below


Here in the example above, we are using format function and its purpose is to display the floating-point numbers up to the digits we have passed in as an argument to it.

It is evident that 0.1 + 0.1 + 0.1 when represented up to 30 digits does not equates to 0.3 and hence it’s not equal to 0.3.


Reason:
0.5 and 0.25 have an exact representation in the floating-point number where as 0.1 do not have an exact representation in floating point number as evident in the above example.



Alternate way to compare floats

Depending upon the use case you are working on, floats can be compared by taking the absolute value of it , subtracting from its actual value and then comparing with some value (tolerance) as per your business use case.



Here in the above example 0.001 is your tolerance value.





Python : About : Variables

  Variables in Python Variables are used to: Name an object. Remind us about the usability of an object. Allow us to reuse same object in mu...