简体   繁体   English

如何在python pandas中更准确地划分数字

[英]How to divide numbers more accurately in python pandas

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.我正在尝试进行计算,将数字1034.55除以 0.05,然后截断所有数字。

If I do 1034.55/0.05 on the Windows and Android calculator, it gives 20691. Within python however, it gives:如果我在 Windows 和 Android 计算器上执行 1034.55/0.05,它给出 20691。但是在 python 中,它给出:

>>> 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.使用浮点数时,精度必须高达 5 位。

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)我目前正在做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.我试图先将数字乘以 100000 以尝试对 integer 进行数学运算,但这增加了太多的性能延迟。 I've also seen there is an import doubles module but this won't be as fast as numpy?我还看到有一个import doubles模块,但这不会像 numpy 一样快吗?

To round it to the nearest integer use round() :要将其四舍五入到最接近的 integer,请使用round()

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

You can just round it to the nearest integer using the built in round() function.您可以使用内置的round() function 将其四舍五入到最接近的 integer。

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:或者,您可以使用数学库中的函数ceil() (总是舍入到较大的数)和floor() (总是舍入到较小的数)来指定它是舍入到更大的还是更小的数:

from math import floor, ceil

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

or要么

import math

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM