如何获取实数而不是复数的输出?

时间:2019-02-23 09:21:07

标签: python python-2.7

我编写了以下代码来求解任何二次多项式,但我希望最终输出为实数(整数或小数),但得到的复数为(3 + 0j)。如何转换它们?

以下是代码:-

import cmath
a = float(raw_input("Enter the Coefficient of x^2 :- "))
b = float(raw_input("Enter the coefficient of x :- "))
c = float(raw_input("Enter the value of constant term or c :- "))

d = ((b*b) - (4*a*c))
if d < 0:
    print "There are no Real Roots of this equation"
else:
    x1 = (((-b) + cmath.sqrt(float(d))) // 2*a)
    x2 = (((-b) - cmath.sqrt(float(d))) // 2*a)

    if x1 == x2:
        print "x = ", x1
    else:
        print "x = ", x1, "or", x2

所需结果:-我希望最终结果是一个实数(包括小数的有理数和无理数都可以)(例如:4、4 / 3等)。

2 个答案:

答案 0 :(得分:2)

仅打印实际部分,除了必须使用const ranges = [{ divider: 1e6, suffix: 'm' }, { divider: 1e3, suffix: 'k' }]; const regx = /^-?\d+(?:.\d{0,1})?/; export function getCurrencyValue(value: number) { // Not allowed to use for-of, and the rule saying not to use it also doesn't like `for` loops, so... return ranges.reduce((formattedValue, { divider, suffix }) => { if (value >= divider) { const match = `${value / divider}`.match(regx); if (match) { formattedValue = `${match[0]}${suffix}`; } } return formattedValue; }, String(value)); // Presumably you always want it to be a string }

2a

答案 1 :(得分:0)

您可以使用诸如Complex之类的类,并支持虚构的解决方案。
 来自http://hplgit.github.io/primer.html/doc/pub/class/._class-solarized005.html

的代码
class Complex(object):
    def __init__(self, real, imag=0.0):
        self.real = real
        self.imag = imag

    def __add__(self, other):
        return Complex(self.real + other.real,
                   self.imag + other.imag)

    def __sub__(self, other):
        return Complex(self.real - other.real,
                   self.imag - other.imag)

    def __mul__(self, other):
        return Complex(self.real*other.real - self.imag*other.imag,
                   self.imag*other.real + self.real*other.imag)

    def __div__(self, other):
        sr, si, or, oi = self.real, self.imag, \ 
                     other.real, other.imag # short forms
        r = float(or**2 + oi**2)
        return Complex((sr*or+si*oi)/r, (si*or-sr*oi)/r)

    def __abs__(self):
        return sqrt(self.real**2 + self.imag**2)

    def __neg__(self):   # defines -c (c is Complex)
        return Complex(-self.real, -self.imag)

    def __eq__(self, other):
        return self.real == other.real and self.imag == other.imag

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        return '(%g, %g)' % (self.real, self.imag)

    def __repr__(self):
        return 'Complex' + str(self)

    def __pow__(self, power):
        raise NotImplementedError\ 
          ('self**power is not yet impl. for Complex')