-2

I was doing my program for a school project when I encountered a problem which I'm unable to understand after trying many different methods to resolve it. I have a function that does a simple mathematical operation like this:

def pikkus(kogupikkus, loimed):
    summa = loimed * (kogupikkus * 1.2 + 0.5)
    return (summa)

Now, when giving the function numbers 4.9 and 140 (in this same order), it returns me a number which isn't true, because 4.9 * 1.2 + 0.5 = 6.38 and 140 * 6.38 = 893.2, but all I get is 893.1999999999999, but it's not even true, try doing 140 * 6.38 yourself - it's exactly 893.2 PS! It has to be a float number, it's in my project instructions that it can't be rounded to an integer, so answers like "just put a round() infront and you are good" don't help me at all.

harlu
  • 9
  • 3
  • See http://0.30000000000000004.com/ – ChrisGPT was on strike Mar 12 '17 at 17:22
  • You could use the [`decimal` module](https://docs.python.org/3/library/decimal.html), but since this is an assignment your instructor may have other ideas. Consider asking them about this. – ChrisGPT was on strike Mar 12 '17 at 17:23
  • 2
    Actually, 893.1999999999999... _is_ equal to 893.2 mathematically, so there's no error here ;) – ForceBru Mar 12 '17 at 17:23
  • @Chris, it's the last program I have to do in this course, and I'm supposed to get it done only using the things I've learned, but we didn't learn anything about decimal modules, so yes, it's not the way it's supposed to work. The instructions even give me the formula I'm using, so there can't be any errors there either. Also, they've shown the end result of the program, and there, it shows perfectly fine. – harlu Mar 12 '17 at 17:32

2 Answers2

0

This has to do with the internal representation of floating point numbers in python. From the docs:

It’s easy to forget that the stored value is an approximation to the original decimal fraction, because of the way that floats are displayed at the interpreter prompt. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. If Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display

0.1 0.1000000000000000055511151231257827021181583404541015625

so you are better of specifying the precision you want, float("{0:.2f}".format(13.949999999999999))

From here

Community
  • 1
  • 1
Priyank
  • 1,513
  • 1
  • 18
  • 36
0

This is a floating point precision problem. If you read the docs it says that this problem is due to it trying to produce numbers that are as accurate as possible, there are ways around this issue such as rounding with the built-in function round() which in your case you could round anywhere after the tenths place and it would fix your problem.

Andria
  • 4,712
  • 2
  • 22
  • 38