在Python中对十进制对象进行除法和乘法 [英] Dividing and multiplying Decimal objects in Python
问题描述
在下面的代码中,coeff1和coeff2都是Decimal对象。当我使用type(coeff1)检查它们的类型时,我得到了( decimal.Decimal类),但是当我进行测试代码并检查了十进制对象时,我得到了十进制。十进制,不带单词类
In the following code, both coeff1 and coeff2 are Decimal objects. When i check their type using type(coeff1), i get (class 'decimal.Decimal') but when i made a test code and checked decimal objects i get decimal. Decimal, without the word class
coeff1 = system[i].normal_vector.coordinates[i]
coeff2 = system[m].normal_vector.coordinates[i]
x = coeff2/coeff1
print(type(x))
system.xrow_add_to_row(x,i,m)
另一个问题是,当我将xrow_add_to_row函数的第一个输入更改为负x时:
another issue is when i change the first input to the function xrow_add_to_row to negative x:
system.xrow_add_to_row(-x,i,m)
我在更改后的代码的上方行上收到无效操作错误:
I get invalid operation error at a line that is above the changed code:
<ipython-input-11-ce84b250bafa> in compute_triangular_form(self)
93 coeff1 = system[i].normal_vector.coordinates[i]
94 coeff2 = system[m].normal_vector.coordinates[i]
---> 95 x = coeff2/coeff1
96 print(type(coeff1))
97 system.xrow_add_to_row(-x,i,m)
InvalidOperation: [<class 'decimal.DivisionUndefined'>]
但是然后在测试代码中我再次使用带负数的Decimal对象和它工作正常。知道可能是什么问题吗?谢谢。
But then again in a test code i use negative numbers with Decimal objects and it works fine. Any idea what the problem might be? Thanks.
推荐答案
decimal.DivisionUndefined
会在尝试进行除法时产生零零。当除数为零( decimal.DivisionByZero
)
decimal.DivisionUndefined
is raised when you attempt to divide zero by zero. It's a bit confusing as you get a different exception when only the divisor is zero (decimal.DivisionByZero
)
>>> import decimal.Decimal as D
>>> D(0) / D(0)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
D(0) / D(0)
decimal.InvalidOperation: [<class 'decimal.DivisionUndefined'>]
>>> D(1) / D(0)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
D(1) / D(0)
decimal.DivisionByZero: [<class 'decimal.DivisionByZero'>]
这篇关于在Python中对十进制对象进行除法和乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!