如何截断python中的浮点不精确度 [英] How to truncate floating points imprecision in python

查看:83
本文介绍了如何截断python中的浮点不精确度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,对于该程序,比较和排列日期序列中的值很重要.但是,我遇到了浮子不精确的问题

I am writing a program for which it is important to compare and rank values in a date series. However, I am running into problems with the imprecision of floats

我正在从我的SQL Server中提取这些应该都是1.6的数据.但是,事实证明它们略有不同(请参见下文).因此,当我使用dataframe.rank()时,它不会将这两个日期视为相同的等级,而是将02/01/2005之上的01/02/2004排名.

I am pulling these data from my SQL server that are both supposed to be 1.6. However, they turn out to be slightly different (see below). Therefore, when I use dataframe.rank(), it doesn't treat these two dates as the same rank, but rather ranks 01/02/2004 above 02/01/2005.

任何人都不知道该如何处理,以便使这两个人的排名相同?

Anyone have any idea how to deal with this so that these two would end up on the same rank?

modelInputData.loc['01/02/2004',('Level','inflationCore','EUR')]
Out[126]: 1.6000000000000003

modelInputData.loc['02/01/2005',('Level','inflationCore','EUR')]
Out[127]: 1.6000000000000001

推荐答案

我建议您像银行家那样做-使用美分和整数而不是EUR/USD和浮点数/小数变量

I would recommend you to do it as bankers do - use cents and integers instead of EUR/USD and float/decimal variables

在MySQL方面将其转换为美分,或在熊猫中进行转换:

either convert it to cents on the MySQL side or do it in pandas:

df['amount'] = round(df['amount']*100)

那么您将遇到的问题要少得多

You'll have much less problems then

这篇关于如何截断python中的浮点不精确度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆