Python Forum
How do I correct multiplication error? Greedy algorithm help
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I correct multiplication error? Greedy algorithm help
#1
I am writing a function using the greedy algorithm and with this algorithm the dollars must be converted to cents.

One of the values is 1.15, however in idle;
1.15*100
114.99999999999999

when I multiply by 100 the output is 114.99999999999999 instead of 115 which messes up the math

Is there another way to convert the dollars to cents?
Reply
#2
There are two misunderstandings here. 
One, not all floating points can be represented perfectly accurately by computers. 
Read more here to understand this issue:  
https://en.wikipedia.org/wiki/Floating-point_arithmetic

The second is that this is mostly a display issue:
>>> 1.15*100
114.99999999999999
>>> print(1.15*100)
115.0
>>>
In terms of money it is often best to do all calculations in cents until the end.

Converting dollars to cents you have a couple options, use the decimal module
>>> from decimal import Decimal
>>> a = Decimal("1.15")
>>> a * 100
Decimal('115.00')
>>>
Or in this case you can probably just use round.
>>> int(round(1.15*100))
115
>>>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  If statements and multiplication elroberto 1 1,661 Jun-22-2022, 05:35 PM
Last Post: deanhystad
  Find the maximum multiplication ercv 3 2,097 Nov-30-2020, 11:55 AM
Last Post: DeaD_EyE
  Greedy Cow Transport Truman 18 9,454 Apr-18-2019, 02:06 PM
Last Post: Truman
  Multiplication Table Homework mcnhscc39 6 4,528 Nov-25-2018, 04:01 PM
Last Post: mcnhscc39
  Syntax error for code that seems correct mcnhscc39 4 3,570 Nov-15-2018, 08:40 PM
Last Post: j.crater
  creating a 3x3 multiplication table aditvaddi 1 3,585 Jun-18-2018, 06:05 AM
Last Post: volcano63
  Multiplication Table funnybone04 4 5,719 Apr-08-2018, 03:03 AM
Last Post: nilamo
  Nested Loop multiplication table SushiRolz 3 10,154 Feb-28-2018, 04:34 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020