Home > Backend Development > Python Tutorial > Why Do Floating-Point Numbers in Python Cause Rounding Errors and How Can They Be Addressed?

Why Do Floating-Point Numbers in Python Cause Rounding Errors and How Can They Be Addressed?

Susan Sarandon
Release: 2024-12-02 21:09:28
Original
811 people have browsed it

Why Do Floating-Point Numbers in Python Cause Rounding Errors and How Can They Be Addressed?

Python's Rounding Error with Floating-Point Numbers

When working with floating-point numbers in Python, it's crucial to be aware of the potential for rounding errors. These errors arise because floating-point numbers can only approximate real numbers, and certain values may be represented differently depending on their proximity to exact powers of two.

For instance, consider the code snippet:

for i_delta in range(0, 101, 1):
  delta = float(i_delta) / 100
  (...)
  filename = 'foo' + str(int(delta * 100)) + '.dat'
Copy after login

In this code, the following values of delta will result in identical files:

  • delta = 0.29 and delta = 0.28999999999999998
  • delta = 0.58 and delta = 0.57999999999999996

This occurs because the exact result of float(29) / 100 is 0.28999999999999998, which is rounded down to 0.28. Similarly, float(58) / 100 is rounded down to 0.57999999999999996.

It's important to note that this rounding error is not systematic and does not affect every integer. To gain further insight into these errors, consider the following code:

import sys

n = int(sys.argv[1])

for i in range(0, n + 1):
  a = int(100 * (float(i) / 100))
  if i != a: print i, a
Copy after login

When run, this code will output pairs of numbers for which the rounding error occurs. By analyzing these pairs, it's possible to identify that the errors tend to occur for numbers that cannot be represented as exact powers of two.

To address this issue, it's recommended to use exact arithmetic where possible and to be aware of the limitations and rounding errors associated with floating-point numbers. For further reading, consult the article "What Every Computer Scientist Should Know About Floating-Point Arithmetic" for a comprehensive guide to this complex topic.

The above is the detailed content of Why Do Floating-Point Numbers in Python Cause Rounding Errors and How Can They Be Addressed?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template