简体   繁体   English

Python中的浮点精度

[英]Floating point precision in Python

I have written this function in python: 我在python中编写了这个函数

import math

def radical(a, b, k): 
    return (1-((a**2-b**2)/a**2)*(math.sin(math.pi*(2*k-1)/180))**2)**.5

def f(a, b): 
 sigma = 0 
 for k in range(1,180/4):
    sigma = sigma + radical(a, b, k)
 return 8*a*math.sin(math.pi/180)*sigma

print f(25.,35.)

When I calculate this function in Wolphramapha and Maple I will get 189.797 but with python I will get 184.91089913 What is the problem in my program? 当我在Wolphramapha和Maple中计算这个函数时,我会得到189.797但是使用python 我会得到184.91089913我的程序有什么问题?

You are off by one. 你是一个人。 The range method excludes the end point. range方法排除终点。 Try adding one: 尝试添加一个:

for k in range(1,180/4 + 1):

Result: 189.797208409 结果: 189.797208409

Well, first of all, python assumes integer division, so there is some serious round off in this code. 好吧,首先,python假设整数除法,所以在这段代码中有一些严重的舍入。 I believe there is an import in division for this. 我认为这有分歧。 Also, Here is some information on python's floating point arithmetic issues/problems: 另外,这里有一些关于python的浮点运算问题/问题的信息:

http://docs.python.org/2/tutorial/floatingpoint.html http://docs.python.org/2/tutorial/floatingpoint.html

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

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