示例代碼:
from decimal import Decimal numStr = '1.13' print('====a', Decimal(numStr) * Decimal('1e8')) print('====b', Decimal(numStr) * Decimal(1e8)) print('====c', Decimal(float(numStr)) * Decimal('1e8')) print('====d', Decimal(float(numStr)) * Decimal(1e8))
輸出結果:
示例代碼輸出結果:
====a 1.13E+8
====b 113000000.00
====c 112999999.9999999893418589636
====d 112999999.9999999893418589636
示例1說明: numStr 1.13 × 1e8期望值是113000000.00,而實際計算過程中因為float精度問題會導致計算結果出現偏差。具體原因可以看文末的參考。示例1是使用Decimal計算的結果對比,可以看出如果要得出期望值時,可以考慮使用b輸出結果的計算方式。
如何提高float精度。示例代碼:
numStr = '1.13' a = float(numStr)*1e8 print('====a', a) print('====b',round(a)) print('====c', round(a,2)) print('====d', round(a,3)) print('====e', '%.3f'%a)
輸出結果:
示例代碼輸出結果:
====a 112999999.99999999
====b 113000000
====c 113000000.0
====d 113000000.0
====e 113000000.000
示例2說明: 示例2是使用round()?方法返回浮點數a的四舍五入值。也可以得到期望值113000000.0,如果需要對計算結果進行小數點保留可以使用e輸出結果的方式。
float double精度,參考:
1、Python之?float浮點數精度問題 - String-Lee - 博客園 (cnblogs.com)https://www.cnblogs.com/String-Lee/p/9840160.html
2、Asking for Help/How can I add or substract two to the last digit of a float? - Python Wikihttps://wiki.python.org/moin/Asking%20for%20Help/How%20can%20I%20add%20or%20substract%20two%20to%20the%20last%20digit%20of%20a%20float%3F?highlight=%28%5CbCategoryAskingForHelpAnswered%5Cb%29
3、
11. Brief Tour of the Standard Library — Part II — Python 3.10.4 documentationhttps://docs.python.org/3/tutorial/stdlib2.html#decimal-floating-point-arithmetic
4、Python3.中的浮點數運算(存在的.99999問題)_小白羊000的博客-CSDN博客https://blog.csdn.net/qq_41447652/article/details/123953908?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-1.pc_relevant_paycolumn_v3&spm=1001.2101.3001.4242.2&utm_relevant_index=4%E2%80%8B
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态