相关疑难解决方法(0)

浮点数的Python舍入错误

我不知道这是否是一个明显的错误,但是在运行Python脚本来改变模拟的参数时,我意识到缺少delta = 0.29和delta = 0.58的结果.经过调查,我注意到以下Python代码:

for i_delta in range(0, 101, 1):
  delta = float(i_delta) / 100

  (...)

filename = 'foo' + str(int(delta * 100)) + '.dat'
Run Code Online (Sandbox Code Playgroud)

为delta = 0.28和0.29生成相同的文件,与.57和.58相同,原因是python返回float(29)/ 100为0.28999999999999998.但这不是一个系统性的错误,在某种意义上它并不是每个整数都会发生的.所以我创建了以下Python脚本:

import sys

n = int(sys.argv[1])

for i in range(0, n + 1):
  a = int(100 * (float(i) / 100))
  if i != a: print i, a
Run Code Online (Sandbox Code Playgroud)

而且我看不到发生此舍入错误的数字中的任何模式.为什么这些特定数字会发生?

python

23
推荐指数
2
解决办法
2万
查看次数

Python数学是错误的

可能重复:
带有浮点数的Python舍入错误

Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> 4.2 - 1.8
2.4000000000000004
>>> 1.20 - 1.18
0.020000000000000018
>>> 5.1 - 4
1.0999999999999996
>>> 5 - 4
1
>>> 5.0 - 4.0
1.0
Run Code Online (Sandbox Code Playgroud)

为什么Python的数学错误?

python math numbers

7
推荐指数
2
解决办法
2万
查看次数

Python奇怪的添加bug

可能重复:
python - 使用浮点数的小数位问题
Python浮点相等的怪异

在下面的代码中,我有percentage一个浮点变量.我设置它以便if number到达10,000,percentage假设上升.01.

# Tries to find a number that when squared and 5%'ed is still a square.

import math

print("Script has started:\n")

percentage = .1
number = 1
while number != -1:
    number = number + 1
    num_powered = number ** 2
    num_5per = num_powered * percentage
    num_5per_sqrt = math.sqrt(num_5per)
    num_list = list(str(num_5per_sqrt))
    dot_location = num_list.index(".")
    not_zero = 0
    for x in num_list[dot_location + 1:]:
        if …
Run Code Online (Sandbox Code Playgroud)

python floating-point addition

1
推荐指数
2
解决办法
6547
查看次数

标签 统计

python ×3

addition ×1

floating-point ×1

math ×1

numbers ×1