Python认为Euler存在身份问题(cmath返回了时髦的结果) [英] Python thinks Euler has identity issues (cmath returning funky results)

查看:147
本文介绍了Python认为Euler存在身份问题(cmath返回了时髦的结果)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

import math
import cmath
print "E^ln(-1)", cmath.exp(cmath.log(-1))

打印内容:

E^ln(-1) (-1+1.2246467991473532E-16j)

它应该打印什么:

-1

(供参考,根据 python.org上的文档 cmath.exp(x)返回e ^ (x),并且cmath.log(x)返回ln(x),因此,除非我缺少分号或其他内容,否则这是一个非常简单的三行程序.

According to the documentation at python.org cmath.exp(x) returns e^(x), and cmath.log(x) returns ln (x), so unless I'm missing a semicolon or something , this is a pretty straightforward three line program.

当我测试cmath.log(-1)时,它返回π i (技术上为3.141592653589793j).哪个是对的. 欧拉的身份说e ^(π i )=- 1,但是Python说我举起e ^(π i )时,我得到某种疯狂的言论(特别是-1+1.2246467991473532E-16j).

When I test cmath.log(-1) it returns πi (technically 3.141592653589793j). Which is right. Euler's identity says e^(πi) = -1, yet Python says when I raise e^(πi), I get some kind of crazy talk (specifically -1+1.2246467991473532E-16j).

为什么Python讨厌我,我该如何安抚它?

Why does Python hate me, and how do I appease it?

是否有一个图书馆可以使它正确地进行数学运算,还是我必须向范·罗苏姆(van Rossum)献祭?也许这是某种浮点精度问题?

Is there a library to include to make it do math right, or a sacrifice I have to offer to van Rossum? Is this some kind of floating point precision issue perhaps?

我遇到的最大问题是精度不够高,以至于在最终函数(未显示)中其他值看起来比实际零更接近于0,因此布尔测试毫无用处(即if(x==0)),所以是局部最小值,等等...

The big problem I'm having is that the precision is off enough to have other values appear closer to 0 than actual zero in the final function (not shown), so boolean tests are worthless (i.e. if(x==0)) and so are local minimums, etc...

例如,在下面的迭代中:

For example, in an iteration below:

X = 2 Y= (-2-1.4708141202500006E-15j)
X = 3 Y= -2.449293598294706E-15j
X = 4 Y= -2.204364238465236E-15j
X = 5 Y= -2.204364238465236E-15j
X = 6 Y= (-2-6.123233995736765E-16j)
X = 7 Y= -2.449293598294706E-15j

3& 7实际上都等于零,但是它们似乎是一堆中最大的虚部,而4和5根本没有它们的实部.

3 & 7 are both actually equal to zero, yet they appear to have the largest imaginary parts of the bunch, and 4 and 5 don't have their real parts at all.

抱歉,提示音.非常沮丧.

Sorry for the tone. Very frustrated.

推荐答案

问题是将有限空间中的无理数(例如π)表示为浮点所固有的.

最好的办法是过滤结果,如果结果值在给定范围内,则将其设置为零.

The best you can do is filter your result and set it to zero if its value is within a given range.

>>> tolerance = 1e-15
>>> def clean_complex(c):
...   real,imag = c.real, c.imag
...   if -tolerance < real < tolerance:
...     real = 0
...   if -tolerance < imag < tolerance:
...     imag = 0
...   return complex(real,imag)
... 
>>> clean_complex( cmath.exp(cmath.log(-1)) )
(-1+0j)

这篇关于Python认为Euler存在身份问题(cmath返回了时髦的结果)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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