educative.io

Educative

Python and Math

A Script was run 10.2*3
The Answer Is 30.6
But when I ran the script it gave me
30.599999999999998 altho it is close it still isn’t exactly correct I wonder if this is a bug or is there another explaination for it
Thank You


Course: Learn Python 3 from Scratch - Free Interactive Course
Lesson: Arithmetic Operators - Learn Python 3 from Scratch

This is a common error that usually occurs in compilers while performing an arithmetic function, it is known as a round-off error. This is because floating-point numbers are represented as base fractions of 2 and thus cannot be saved as a perfect precision. These numbers are Instead approximated by a finite number of bytes. Round-off error is known as the difference between this approximation and the actual correct value.

In this case, we can perform
print(round((10.2*3),1))
to get the accurate output of the arithmetic.