Python float division "rounding error" on division by 100

ARF

When dividing a float by 100 in Python 2.7 I get the following "rounding behaviour":

>>> 3.7e-03/100
3.7000000000000005e-05

I would expect the following:

>>> 3.7e-03/100
3.7e-05

Note that:

>>> 3.7e-03/100 == 3.7e-05
False
>>> 3.7000000000000005e-05 == 3.7e-05
False

While probably of not practical difference in most applications I find this behaviour somewhat disconcerting.

Why does this happen and how can I avoid it?

I am using Python: '2.7.5 |Anaconda 1.7.0 (32-bit)| (default, Jul 1 2013, 12:41:55) [MSC v.1500 32 bit (Intel)]'

user4815162342

This is a well-known deficiency of floating-point numbers.

You can think of binary floating-point as fractions with power-of-two denominators. Even a simple number such as 0.1 cannot be accurately represented as binary floating-point, and every division by a power of ten is by nature inaccurate.

If you need accurate division with arbitrary denominators in Python, use Decimal (which simulates pencil-and-paper decimals) or Fraction (which simulates pencil-and-paper fractions).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Python - Float Division by Zero?

From Dev

Increase Accuracy of float division (python)

From Dev

python float division does not work

From Dev

Increase Accuracy of float division (python)

From Dev

Integer division, or float multiplication?

From Dev

float numbers division bash

From Dev

integer division to float result

From Dev

Integer division, or float multiplication?

From Dev

Float Static Cast for Division

From Dev

Getting NaN on float division

From Dev

integer division to float result

From Java

What is the reason for difference between integer division and float to int conversion in python?

From Dev

python ZeroDivisionError: float division by zero - how to treat it as an exception

From Dev

What is the reason for difference between integer division and float to int conversion in python?

From Dev

ZeroDivisionError: float division by zero even after using python future module

From Dev

Numpy array integer / float division

From Dev

PHP Division Float Value Issue

From Dev

Numpy array integer / float division

From Dev

Dividing float by int and storing as float - Division by zero

From Dev

Printing % from division in Python

From Dev

Python: Division by Larger Number

From Dev

Python 3 strange division

From Dev

Incorrect fraction division in python

From Dev

Division of Polynomials in python

From Dev

Division by 3 in Python

From Dev

Python getting division by zero

From Dev

Rest of the division in python

From Dev

Division exception in MYSQL or Python

From Dev

Python division by 10