PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How do I get a Decimal square root of a negative Decimal number in Python?

 August 10, 2022     decimal, python     No comments   

Issue

To get the sqaure root of a negative number we could use cmath.sqrt. But either the real part or the imag part of the result is still a float:

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

result: float

How do I get a Decimal square root of a negative Decimal number?

For a positive number we could use: Decimal (8).sqrt ()

The result is still a Decimal. But it doesn't work on negative numbers: Decimal (-8).sqrt ()

{InvalidOperation}[]


Solution

You could implement a ComplexDecimal() class with that functionality.

Here is some code to get you going:

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'>

and then you need to implement multiplication, division, etc. yourself, but that should be pretty straightforward.



Answered By - norok2
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing