Jacob Lee
Jacob Lee

Reputation: 73

How to fix python int casting error?

I'm attempting Project Euler problem 484. I'm in the beginning stages of the problem and am just searching for patterns in the numbers.

The problem requests me to find an "arithmetic derivative". For example, to find the arithmetic derivative of 60:

60 = 2^2 * 3^1 * 5^1

60' = (2/2 + 1/3 + 1/5) * 60 = 92

I utilized the built in primefac algorithm, and created a method for the arithmetic derivative. Here is my code:

import primefac

def ad(n):
  ans = 0
  for i in set(primefac.primefac(n)):
    ans += 1.0*list(primefac.primefac(n)).count(i)/i
  return n*ans

print ad(30) ,  31.0 // PRINTS 31.0 31.0
print int(ad(30))    // PRINTS 30
print ad(30) == 31.0 // PRINTS False

Python casts 31.0 as an int to 30. Is this a floating point error? What is more perplexing is that ad(30) prints 31.0 but returns False when evaluated against each other.

Upvotes: 2

Views: 212

Answers (1)

glibdud
glibdud

Reputation: 7850

Yes, this is a floating point issue. There's an easy fix, though... since n will always by definition be evenly divisible by i, you can cut out the floating point math entirely:

def ad(n):
    ans = 0
    for i in set(primefac.primefac(n)):
        ans += n * list(primefac.primefac(n)).count(i) // i
    return ans

Upvotes: 2

Related Questions