user3274191
user3274191

Reputation: 1

Wrong answer in Python

I was trying to solve this in Python. (10**22+1)/89 which gives me this answer: 1.1235955056179775e+20 So I use the print statement to get the full number "%1.1f" %x and I get this number: 112359550561797750784.0

Here's what's wrong. When you multiply this answer with 89, you don't get 10^22 + 1 but you get 9999999999999999819776. A little playing around by hit & trial gives me the correct answer as 112359550561797752809 which when multiplied by 89 yields the exact 10^22 + 1.

My question, what am I doing wrong to get the last 4 digits of my answer wrong?

Upvotes: 0

Views: 1610

Answers (2)

user2357112
user2357112

Reputation: 282016

This is just how floating-point math works. When you divide 1 by 3 in decimal, you get

0.3333333333333333...

You have to cut that off at some point:

0.3333333333333333

and then when you multiply it by 3:

0.9999999999999999

you don't get 1. Rounding error inevitably accumulates. It's the same in the binary floating-point math Python uses. Even when the result is a whole number (which it is for (10**22+1)/89), floating-point representation can only keep so many digits, so huge numbers can lose some accuracy at the end.

If you want to do this in integer math, you can use the // operator:

>>> ((10**22 + 1) // 89) * 89 == 10**22 + 1
True

// will take the floor of the result if the result isn't an integer:

>>> 5 // 3
1
>>> (5 // 3) * 3
3

Unlike floating-point, Python's integer representations will keep every digit. Unfortunately, this is only practical for integers, as we can't fit every digit of numbers like sqrt(2) or pi into a finite amount of RAM.

Upvotes: 7

RattleyCooper
RattleyCooper

Reputation: 5207

Which number are you trying to get?

If you use the math module you can do this:

import math
e = pow(10, 22) + 1
a = e / 89

This gave me 112359550561797752809L

But without knowing which one of your answers you are trying to get, and not wanting to do the math, I can't tell if this is what you are looking for.

Upvotes: 0

Related Questions