Thank you for your replies. I suspect the solution is a bit more advanced than where I'm at now, which is chapter 2 of a beginner's book. Not sure why the author chose to use examples using money calculations when other calculations that don't need rounding would have sufficed. I will have to revisit this issue when I'm further along.
On Wed, Oct 23, 2013 at 8:44 PM, Danny Yoo <d...@hashcollision.org> wrote: > > > > On Wed, Oct 23, 2013 at 4:13 PM, Alan Gauld <alan.ga...@btinternet.com>wrote: > >> On 23/10/13 22:39, Shelby Martin wrote: >> >>> I've looked online but I'm confused - I need to keep it so that the >>> following program limits the output to two decimal places since it deals >>> in currency. >>> >> >> Its generally a bad idea to use floats when dealing with currency since >> they can introduce small errors which can accumulate over time. It's better >> to either use the Decimal module or to convert money to cents/.pennies and >> then convertback to dollars for display purposes. >> > > > Hi Shelby, > > > If you want to read some gory details, you can find the reasons for why > it's unsafe to represent currency with "floating point" numbers. There's a > classic paper called "What Every Computer Scientist Should Know About > Floating-Point Arithmetic": > > http://www.validlab.com/goldberg/paper.pdf > > and you probably don't want to read the whole thing. :P A rough gist of > the problem: traditional, engineering-focused computer math has a > particular trade-off that most programmers do not realize at first: it > trades accuracy for speed. The native hardware of your computer does > calculations in base-2 rather than base-10 arithmetic. Unfortunately, that > means that fractional quantities take a representational hit: your computer > cannot accurately represent certain decimals in base-2. > > It turns out that this floating point arithmetic limitation is not so bad > for a lot of important applications. But it doesn't bode well at all for > applications that deal with money. There are libraries in Python that > avoid using the built-in floating point hardware, such as the Decimal > library that Alan noted. Computations with it are slower, but that's an > acceptable price for getting the dollars and cents right. If we would do > this sort of thing in the real world, we'd use something like the Decimal > library. You'll see equivalent kinds of libraries in other programming > languages, like the BigDecimal class in Java. >
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor