【问题标题】:How do I get a Decimal square root of a negative Decimal number in Python?如何在 Python 中获得负十进制数的十进制平方根?
【发布时间】:2020-04-03 21:29:40
【问题描述】:

要获得负数的平方根,我们可以使用 cmath.sqrt。但是结果的实部或图像部分仍然是浮点数:

type (cmath.sqrt (Decimal (-8)).imag)

结果:浮动

如何获得负十进制数的十进制平方根?

我们可以使用正数:Decimal (8).sqrt ()

结果仍然是十进制。但它不适用于负数:Decimal (-8).sqrt ()

{无效操作}[]

【问题讨论】:

  • 这能回答你的问题吗? Decimal module and complex numbers in Python
  • @ThierryLathuille 对于cmath() 是的,但一般来说,像complex 本质上是float (float, float) 的2 元组,您可以扩展decimal 模块来处理complex数字作为 Decimal 的 2 元组。它只是没有实现。
  • 您实际需要多少复数功能?

标签: python decimal


【解决方案1】:

您可以实现具有该功能的ComplexDecimal() 类。

这里有一些代码可以帮助你:

from decimal import Decimal


class ComplexDecimal(object):
    def __init__(self, value):
        self.real = Decimal(value.real)
        self.imag = Decimal(value.imag)

    def __add__(self, other):
        result = ComplexDecimal(self)
        result.real += Decimal(other.real)
        result.imag += Decimal(other.imag)
        return result

    __radd__ = __add__

    def __str__(self):
        return f'({str(self.real)}+{str(self.imag)}j)'

    def sqrt(self):
        result = ComplexDecimal(self)
        if self.imag:
            raise NotImplementedError
        elif self.real > 0:
            result.real = self.real.sqrt()
            return result
        else:
            result.imag = (-self.real).sqrt()
            result.real = Decimal(0)
            return result
x = ComplexDecimal(2 + 3j)
print(x)
# (2+3j)
print(x + 3)
# (5+3j)
print(3 + x)
# (5+3j)

print((-8) ** (0.5))
# (1.7319121124709868e-16+2.8284271247461903j)
print(ComplexDecimal(-8).sqrt())
# (0+2.828427124746190097603377448j)
print(type(ComplexDecimal(8).sqrt().imag))
# <class 'decimal.Decimal'>

然后你需要自己实现乘法、除法等,但这应该很简单。

【讨论】:

  • 非常感谢您的帮助!它确实有效,但我不得不问一个愚蠢的问题:我如何实现乘法之类的?
  • @Mason 您需要实现相应的方法,例如__mul____rmul__ 用于乘法运算。请参阅operator 以获取您可能想要实现的方法的列表。当然,你必须自己算算。
【解决方案2】:

你可以x ** 0.5 其中x是一个负数,例如:

>>> x = -10
>>> x ** 0.5
(1.9363366072701937e-16+3.1622776601683795j)

【讨论】:

  • 这不会返回基于Decimal 的值,Decimal(-10) ** 0.5 只会抛出TypeError,而Decimal(-10) ** Decimal(0.5) 会抛出InvalidOperation
猜你喜欢
  • 2018-06-29
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 2018-06-21
  • 2014-11-30
  • 2016-07-18
  • 1970-01-01
相关资源
最近更新 更多