I made the following code to solve any quadratic polynomial but I want the final output to be a Real Number (Either a whole number or a fraction) but I get Complex numbers like (3+0j). How to convert them?
Here is the Code:-
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
Desired Result:- I want the final result to be a Real Number(both Rational and irrational is allowed including fractions)(Like: 4, 4/3 or something like that).
Simply only print the real part, besides you have to devide by 2a
x1 = (((-b) + cmath.sqrt(float(d))) / (2*a))
x2 = (((-b) - cmath.sqrt(float(d))) / (2*a))
if x1 == x2:
print "x = ", x1.real
else:
print "x = ", x1.real, "or", x2.real
You can use a class like Complex and support imaginary solutions as well.
Code taken from 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')
Related
How to properly print the output str
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return Complex(self.real+other.real, self.imaginary+other.imaginary)
def __sub__(self, other):
return Complex(self.real-other.real, self.imaginary-other.imaginary)
def __str__(self):
return '{} & {}i'.format(self.real, self.imaginary)
if __name__ == '__main__':
c = map(float, input().split())
d = map(float, input().split())
x = Complex(*c)
#print (x)
y = Complex(*d)
#print (y)
print(*map(str, [x+y, x-y]), sep='\n')
Input
2 1
5 6
Output
7.0 & 7.0i
-3.0 & -5.0i
Expected out if for addtion it should print + and for substraction it should print -
7.00+7.00i
-3.00-5.00i
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return Complex(self.real+other.real, self.imaginary+other.imaginary)
def __sub__(self, other):
return Complex(self.real-other.real, self.imaginary-other.imaginary)
def __str__(self):
return '{:.2f}{}{:.2f}i'.format(self.real, '+' if self.imaginary >= 0 else '', self.imaginary)
if __name__ == '__main__':
c = map(float, input().split())
d = map(float, input().split())
x = Complex(*c)
#print (x)
y = Complex(*d)
#print (y)
print(*map(str, [x+y, x-y]), sep='\n')
You should manually add sign, if var is positive.
Also in your expected result you have 2 decimal points, so you need to add {:.2f}.
Use this in your str implementation.
def __str__(self):
return f"{self.real}{ '+' if self.imaginary >= 0 else ''}{self.imaginary}i"
Instead of this:
def __str__(self):
return '{} & {}i'.format(self.real, self.imaginary)
You could do this:
def __str__(self):
def __map_imaginary(imag):
if imag > 0:
return "+{:2f}i".format(imag)
if imag < 0:
return "{:2f}i".format(imag)
if imag == 0:
return ""
return "{}{}".format(self.real, __map_imaginary(self.imag))
I have assumed that you don't want to print imaginary part if it equals to 0. You can change that at will.
I've been attempting to complete one of my subjects for the OOP, but I couldn't manage to figure out what's wrong with the definition of my functions. I'm a newbie in this language, already searched the forums but I couldn't find anything useful.
Error message:
Traceback (most recent call last):
File "/home/main.py", line 44, in
add(x, y)
NameError: name 'add' is not defined
This is the program I wrote.
class Complex(object):
def __init__(self, r = 0, i = 0):
self.r = r
self.i = i
def __str__ (self):
return "%s + i%s" % (self.r, self.i)
def add (self, other):
summ = Complex()
summ.r = self.r + other.r
summ.i = self.i + other.i
return "Sum is %d" % summ
def dif (self, other):
dif = Complex()
dif.r = self.r - other.r
dif.i = self.i - other.i
return dif
def multiply (self, other):
multiply = Complex()
multiply.r = self.r * other.r
multiply.i = self.i * other.i
return "%d" % (-1 * multiply.r * multiply.i)
def divide (self, other):
divide = Complex()
divide.r = self.r / other.r
divide.i = self.i / other.i
return "%d" % (divide.r / divide.i)
x = Complex()
y = Complex()
x.r = int(input("Type in real part of x: \n"))
x.i = int(input("Type in imaginary of x: \n"))
print (x, "\n")
y.r = int(input("Type in real part of y: \n"))
y.i = int(input("Type in imaginary of y: \n"))
print (y, "\n")
add(x, y)
The add() function is a member of the Complex class but you are calling it on its own.
You need to call it like this
x.add(y)
When a function is a member of a class like below:
class Complex(object):
def add (self, other):
# Do stuff
The object the function is called on automatically gets passed as self.
So if you call x.add(y), self will be x and other will be y.
If add is a method of your class Complex, then you must write x.add(y) instead of add(x, y).
I know that it is confusing in Python. You need always to apply the "self" as first argument of a method, although it is not an argument, but the object whose method you call.
I am trying to write a simple implementation of elliptic curves in python.
So I have a simple Elliptic Curve class:
class EllipticCurve:
O ="O";
def __init__(self,a,b):
self.a = a
self.b = b
def __eq__(self, other):
if isinstance(other, EllipticCurve):
return self.a == other.a and self.b == other.b
return NotImplemented
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return result
return not result
#property
def discriminant(self):
return 4*a**3+27*b**2
and a class for Points on an Elliptic Curves:
class Point:
def __init__(self,ec):
self.ec = ec
self = ec.O
def __init__(self,ec,x,y):
self.ec = ec
self.x = x
self.y = y
def __add__(self, other):
if self.ec != other.ec:
raise ValueError('These points are on different curves')
if self == self.ec.O:
return Point(ec, other.x, other.y)
if other == self.ec.O:
return Point(ec, self.x, self.y)
if self.x==other.x and self.y==-other.y:
return O
if self==other:
k = 3*(self.x**2+self.ec.a)/(2*self.y)
x3 = k**2-self.x-other.x
return Point(self.ec, x3,k*(self.x-x3)-self.y)
k = (other.y-self.y)/(other.x-self.x)
x3 = k ** 2 - self.x - other.x
return Point(self.ec, x3, k*(self.x - x3) - self.y)
def __eq__(self, other):
if isinstance(other, Point):
return self.x == other.x and self.y == other.y and self.ec == other.ec
return NotImplemented
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return result
return not result
def __neg__(self):
if self==self.ec.O:
return O
return Point(E,self.x,-self.y)
def __sub__(self, other):
return self + -other
and although I would like to add some functionalities to them, they work with actual int values for a,b and x,y.
However, my problem is when I try to use sympy and use 'symbols' for a,b and x,y.
Ideally, my goal is to computationally prove the associative property for 3 points on an elliptic curve, ie, (P+Q)+R = P+(Q+R).
Now, I am able to get a correct result for P+Q:
a,b = symbols('a b')
x1,y1 = symbols('x1 y1')
x2,y2 = symbols('x2 y2')
x3,y3 = symbols('x3 y3')
E = EllipticCurve(a,b)
P = Point(E,x1,y1)
Q = Point(E,x2,y2)
R = Point(E,x3,y3)
P+Q
print(simplify((P+Q).x))
which outputs, correctly:
-x1 - x2 + (y1 - y2)**2/(x1 - x2)**2
Moreover, if I do this:
expr = (P+Q)+R
print(simplify(expr.x))
I get, also (I think) correctly:
x1 + x2 - x3 + (y1 + y3 - (y1 - y2)*(2*x1 + x2 - (y1 - y2)**2/(x1 - x2)**2)/(x1 - x2))**2/(x1 + x2 + x3 - (y1 - y2)**2/(x1 - x2)**2)**2 - (y1 - y2)**2/(x1 - x2)**2
However, if I do:
expr = (P+Q)+R
expr2 = P+(Q+R)
print(simplify((expr-expr2).x))
It takes forever, and if I try:
expr = (P+Q)+R
expr2 = P+(Q+R)
print((expr-expr2).x)
It also return an expression that seems reasonable and I think correct.
But I need to simplify it and to return 0 to prove that expr and expr2 are equal.
Any suggestions on what I am doing wrong ?
print((expr-expr2).x)
Probably you can't get 0 in a general case, because your result expression depends on x1, y1, x2, y2, x3, y3, which don't depend on each other, and if these points do not belong to the same elliptic curve, the result will not be 0. If you try to use (expr-expr2).x.subs ... using different args xi, yi, you can check that (expr-expr2).x is not zero constant.
How do I create the divide method in Python?
This is my code:
# Rational numbers
def gcd(bigger, smaller):
'''compute the greatest common divisor of two positive integers'''
#print(' in gcd ')
if not bigger > smaller :
bigger, smaller = smaller, bigger
while smaller != 0:
remainder = bigger % smaller
#print('gcd calc, big:{}, small:{}, rem:{}'.format(bigger, smaller, remainder))
bigger, smaller = smaller, remainder
return bigger
def lcm(a, b):
'''calculate the least common multiple of two positive integers'''
#print(' in lcm ')
return (a*b)//gcd(a,b)
class Rational(object):
'''Rational with numerator and denominator. Denominator defaults to 1'''
def __init__(self, numer, denom = 1):
#print('in constructor')
self.numer = numer
self.denom = denom
def __str__(self):
'''String representation for printing'''
#print(' in str ')
return str(self.numer) + '/' + str(self.denom)
def __repr__(self):
''' Used in the interpreter. Call __str__ for now'''
print(' in repr ')
return self.__str__()
def __add__(self, param_Rational):
'''Add two Rationals'''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
# find the lcm
the_lcm = lcm(self.denom, param_Rational.denom)
# multiply each numerator by the lcm, then add
numerator_sum = the_lcm*self.numer/self.denom + \
the_lcm*param_Rational.numer/param_Rational.denom
return Rational( int(numerator_sum), the_lcm )
else:
print("Wrong type in addition method.")
raise(TypeError)
def __sub__(self, param_Rational):
'''Subtract two Rationals'''
#print(' in add ')
# find the lcm
the_lcm = lcm(self.denom, param_Rational.denom)
# multiply each numerator by the lcm, then add
numerator_sum = the_lcm*self.numer/self.denom - \
the_lcm*param_Rational.numer/param_Rational.denom
return Rational( int(numerator_sum), the_lcm )
def reduce_rational(self):
'''Return the reduced fraction value as a Rational'''
# find the gcd and divide numerator and denominator by it
the_gcd = gcd(self.numer, self.denom)
return Rational( self.numer//the_gcd, self.denom//the_gcd)
def __eq__(self, param_Rational):
'''Compare two Rationals for equalit and return a Boolean'''
reduced_self = self.reduce_rational()
reduced_param = param_Rational.reduce_rational()
return reduced_self.numer == reduced_param.numer and\
reduced_self.denom == reduced_param.denom
def __mul__(self, param_Rational):
''' Multiply two Rationals '''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
#multiply
denom_zero_check = self.denom
second_denom_zero_check = param_Rational.denom
if denom_zero_check & second_denom_zero_check > 0:
numer_mul = self.numer*param_Rational.numer
denom_mul = self.denom*param_Rational.denom
return Rational(int(numer_mul),int(denom_mul))
else:
print("Denominator can't be zero.")
else:
print("Wrong type in subtraction method")
raise(TypeError)
""" """
def __truediv__(self): # <-------- Here is where TypeError occurs #
''' Divide two Rationals '''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
#multiply
denom_zero_check = self.denom
second_denom_zero_check = param_Rational.denom
if denom_zero_check & second_denom_zero_check > 0:
numer_mul = self.numer*param_Rational.denom
denom_mul = self.denom*param_Rational.numer
return Rational(int(numer_mul),int(denom_mul))
else:
print("Denominator can't be zero.")
And I'm getting the error (location marked above):
TypeError: __truediv__() takes 1 positional argument but 2 were given
How do I fix this? I got the multiplication down but not the divide, should I use div or truediv? And do I need to use / in the actual div method?
How can __truediv__ only take one argument? You need two, self and the divisor. The same way your __mul__ __add__, and __sub__ needed a second argument.
def __truediv__(self, param_Rational):
# rest of your code
Instead of first printing an error message and then raising the error, you can use:
raise TypeError("Wrong type in addition method.")
Also, it might be usefull to check wether the demnominator is 0 or not in init(), and raise ZeroDivisionError if it is.
PS: 2/3 / 6/9 should equal 1/1 as 2/3=6/9=0.666...
This is my program (a very simple one):
__author__="soham"
__date__ ="$Aug 12, 2012 4:28:51 PM$"
from math import sqrt
class Point:
x = 0;
y = 0;
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.__dict__ == other.__dict__
def get_dist(self, other):
return sqrt(abs((self.x - other.x)^2 + (self.y - other.y)^2))
def is_rect(self,other,another,yet_another):
return (self.get_dist(other) == another.get_dist(yet_another)) and \
(self.get_dist(another) == other.get_dist(yet_another)) and \
(self.get_dist(yet_another) == other.get_dist(another))
a, b, c, d = Point(4,3),Point(4,9), Point(7,3), Point(7,9)
if a.is_rect(b,c,d):
print "Rectangle."
else:
print "No, not a rectangle!"
This returns no. A similar program written in Java returns the expected answer.
I'm very new to Python. Help!
Exponentiation in Python is **, not ^.
^ in Python is actually the bitwise xor operator.
For exponentation, you can also do pow(x,y) instead of x**y.