Home > database >  How to divide numbers more accurately in python pandas
How to divide numbers more accurately in python pandas

Time:12-14

I'm trying to make a calculation which takes in the number 1034.55 and divide it by 0.05 and then truncate off all the numbers.

If I do 1034.55/0.05 on the Windows and Android calculator, it gives 20691. Within python however, it gives:

>>> 1034.55/0.05
20690.999999999996

Obiously when I truncate the decimal places, this is now one lower number than expected. When working with floats, There must be up to 5 digits accuracy.

How am I able to solve this rounding issue due to floating point accuracy(?) while keeping the performance? I am currently doing chunk["index"] = np.trunc(chunk["num"] / 0.05)

I have tried to multiply the number by 100000 first to try and do maths on an integer but this added too much delay in the performance. I've also seen there is an import doubles module but this won't be as fast as numpy?

CodePudding user response:

To round it to the nearest integer use round():

int(round(num/0.05),5))

CodePudding user response:

You can just round it to the nearest integer using the built in round() function.

Alternativly you can specify if it rounds to the bigger or smaller number using the functions ceil() (always to bigger number) and floor() (alway to smaller number) from the math library:

from math import floor, ceil

mynumber = floor(mynumber)
mynum = ceil(mynum)

or

import math

mynumber = math.floor(mynumber)
mynum = math.ceil(mynum)
  • Related