0

I've been trying to solve this problem:

The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.

You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?

And this is my code

import math

def find_nb(m):

nb = 1
nb_vol = 0

while True:
    nb_vol += math.pow(nb, 3)

    if (nb_vol == m):
        return nb
    elif (nb_vol > m):
        return -1

    nb += 1

Now, when I try to solve for find_nb(2521115597681328384) it returns -1 when it should in fact return 56352. If I change

nb_vol += math.pow(nb, 3)

to

nb_vol += nb ** 3

Everything works correctly. Why?

KNY
  • 35
  • 3
  • 5
    Does this answer your question? [Exponentials in python x.\*\*y vs math.pow(x, y)](https://stackoverflow.com/questions/20969773/exponentials-in-python-x-y-vs-math-powx-y) – Reznik Dec 14 '19 at 14:31
  • @Reznik That question talks more about performance than correctness. – Anonymous Dec 14 '19 at 14:39
  • for completeness go here to check if two floats are close enough to be called equal https://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python – MjH Dec 14 '19 at 14:46
  • @Anonymous The question itself answers this question. – chepner Dec 14 '19 at 14:55

1 Answers1

0

math.pow always converts it’s arguments to floats first, which are only approximations.

The ** operator uses integers that can never overflow, which means that it always gives a correct result.

Anonymous
  • 11,748
  • 6
  • 35
  • 57