Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating Point Limitations [duplicate]

My code:

a = '2.3'

I wanted to display a as a floating point value.

Since a is a string, I tried:

float(a)

The result I got was :

2.2999999999999998

I want a solution for this problem. Please, kindly help me.

I was following this tutorial.

like image 958
user46646 Avatar asked Jan 02 '09 09:01

user46646


People also ask

What are the limitations of floating-point representation?

As a result, they do not represent all of the same values, are not binary compatible, and have different associated error rates. Because of a lack of guarantees on the specifics of the underlying floating-point system, no assumptions can be made about either precision or range.

Why is floating-point inaccurate?

Floating-point decimal values generally do not have an exact binary representation due to how the CPU represents floating point data. For this reason, you may experience a loss of precision, and some floating-point operations may produce unexpected results.

Do floats use less memory than doubles?

double has higher precision, whereas floats take up less memory and are faster. In general you should use float unless you have a case where it isn't accurate enough. On typical modern computers, double is just as fast as float.


2 Answers

I think it reflects more on your understanding of floating point types than on Python. See my article about floating point numbers (.NET-based, but still relevant) for the reasons behind this "inaccuracy". If you need to keep the exact decimal representation, you should use the decimal module.

like image 144
Jon Skeet Avatar answered Oct 18 '22 14:10

Jon Skeet


This is not a drawback of python, rather, it is a drawback of the way floating point numbers are stored on a computer. Regardless of implementation language, you will find similar problems.

You say that you want to 'display' A as a floating point, why not just display the string? Visually it will be identical to what you expect.

As Jon mentioned, if your needs are more than just 'displaying' the floating point number, you should use the decimal module to store the exact representation.

like image 26
Mike Hamer Avatar answered Oct 18 '22 15:10

Mike Hamer