如何获得Python中的负十进制数的小数平方根是多少?

梅森:

为了让我们可以使用cmath.sqrt负数的sqaure根。但无论实部或结果的IMAG部分仍然是一个浮动:

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

结果:浮法

我如何获得一个负的十进制数的小数平方根是多少?

对于一个正数,我们可以使用: Decimal (8).sqrt ()

其结果仍然是一个小数。不过,这并不在负数工作:Decimal (-8).sqrt ()

{InvalidOperation} []

norok2:

你可以实现一个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'>

然后你需要实现乘法,除法,等自己,但应该是相当简单的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章