简体   繁体   中英

Wrong code or strange math behavior? (python 3)

I'm calculating with variables by multiplicating etc and I noticed this strange behavior.

If I use these calculations:

CD = 6
CDR = 0.4

CD = float(CD) - (float(CDR) * float(CD))

Theoretically that would be 6 - (6 * 0.4) = 6 - 2.4 = 3.6 if I then print(CD) it prints

3.5999999999999996

Is there a reason for this which I can avoid? Is there a way, like math.ceil to round up the number but to a certain decimal, for example to x.xxxxx (5th deciamal)?

(Let me know if I did anything wrong in this post, I find answers on this site since a while but have never posted before so I maybe did something wrong, apologies in advance.)

you can try the decimal module, but under the hood your answer is still "correct". It's just how floating point numbers convert to decimal representations.

You're running in to floating point arithmetic problems. Trying using decimal.Decimal instead of float .

If it's for display only (or piece of mind) you can do

x = math.ceil(x*100000.0) / 100000.0

However there's no guarantee that the will be a number that can be represented exactly in memory either (ending up with the same 3.599999999..)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM