Potato
Potato

Reputation: 51

Python 3 code is not performing as expected, Giving incorrect numbers

I've recently gotten into Python, and I couldn't come up with any things to make. So i decided i'd port all of my Project Euler stuff over to Python just to have something to do. But basically, the code below is supposed to find the product of a, b, and c, where a + b + c = 1000. (Pythagorean triplet)

from math import sqrt

def solve():
    product = 0
    for a in range(1, 500):
        for b in range(1, 500):
            needed = sqrt(a*a + b*b)
            if a + b + needed == 1000:
                    product = a * b * needed
                    return product
    return product

print(solve())

This code produces the correct result, which is 31875000.0. I want it to return an integer, and not a floating point value. I tried doing

needed = round(sqrt(a*a + b*b))

but for some reason, this returns the number 498002, which is not even close to being the same number. I've also tried using Floor from the math library, but that also does the same thing, as well as int(). Is there something that I'm overlooking? Or is this a bug? Or what. I'm using Python 3.5 if that matters.

Upvotes: 2

Views: 49

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90899

Because when you round() off, or even do int() to convert the sqrt() result to integer, you are losing precision, like in case of i being 2 and j being 499 , since i is so small , the sqrt of a^2 + b^2 would be something like - 499.0040079999358 - rounding that off would give 499 . And your program would wrongly assume this to be a triplet ,since 499 + 499 + 2 is 1000.

Instead of rounding the result of sqrt you should convert the product to integer before returning. Example -

from math import sqrt

def solve():
    product = 0
    for a in range(1, 500):
        for b in range(1, 500):
            needed = sqrt(a*a + b*b)
            if a + b + needed == 1000:
                    product = a * b * needed
                    return int(product)
    return product

print(solve())

Upvotes: 2

Related Questions