如何在python中以指定精度计算立方根?
我们怎么能在Python中计算立方根,并且指定精度呢?
我想用decimal这个类来实现,而且我的编程环境是Python 2.5。
我试过用类似这样的代码:
>>> from decimal import *
>>> x=Decimal("10")
>>> print x**(Decimal("1.0")/3)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
print x**(Decimal("1.0")/3)
File "C:\Python25\lib\decimal.py", line 1752, in __pow__
return context._raise_error(InvalidOperation, 'x ** (non-integer)')
File "C:\Python25\lib\decimal.py", line 2325, in _raise_error
raise error, explanation
InvalidOperation: x ** (non-integer)
>>>
这个方法在Python 2.6及之后的版本可以用,但在Python 2.5中不行?有没有什么解决办法?
2 个回答
1
根据在http://www.python.org/download/releases/2.5.5/NEWS.txt上发布的更新说明,2.5.2版本对小数模块进行了很多错误修复和更新。如果你现在使用的是2.5.0或2.5.1版本,能不能升级到2.5.2呢?
2
在2.5.2版本中肯定是可以用的,可能在2.5版本之后有了什么变化?
Python 2.5.2 (r252:60911, Jan 20 2010, 21:48:48)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import Decimal
>>> x=Decimal("10")
>>> x**(Decimal("1.0")/3)
Decimal('2.154434690031883721759293566')