Search code examples
pythoncastingint

Casting using int() turns 16.0 to 15


So I have a weird problem when trying to cast a float number to an integer. My code currently looks like this:

from math import gcd 
def dostuff(n,m):
    L = np.sqrt(n**2+m**2+n*m)
    dR = gcd(2*m+n,2*n+m)
    atoms=4*L**2/dR
    print(atoms)
    atoms = int(atoms)
    print(atoms)

When I run this code with n=4 and m=4, the first print returns 16.0, while the second print returns 15. What is the reason for this, and is there anything I can do to make the second one return 16 instead?


Solution

  • have you tried a round function? round(atoms) it will round to the nearest integer 5.6 will be 6 and 5.4 will be 5 if you want to go up use ceil(atoms) otherwise floor(atoms). hope this helps you!