Reputation: 241
I am writing a code in Python 2.7 that calculates the root of a quadratic equation. However the outputs are of the form 1.41421356237 for example.... Is there a way to produce its square root form (sqrt(2))?
Here is my code:
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
import scipy
import scipy.special as sp
import scipy.integrate as integrate
import pylab as pylab
import math
import cmath
alpha = input('Enter alpha: ')
c = 1/alpha
a = 1
b = 1
d = b**2 - 4*a*c
if d<0:
s1 = (-b+cmath.sqrt(d)) / (2*a)
s2 = (-b-cmath.sqrt(d)) / (2*a)
print "Two Complex Solutions: ",s1, " and",s2
elif d==0:
s = (-b+math.sqrt(d))/ (2*a)
print "One real solution: ",s
else:
s1 = (-b+math.sqrt(d)) / 2*a
s2 = (-b-math.sqrt(d)) / 2*a
print "Two real solutions: ",s1," and",s2
This is an example of the output which i need in square root form:
Enter alpha: 6
Two real solutions: -0.211324865405 and -0.788675134595
Upvotes: 2
Views: 2566
Reputation: 856
Python by default is eager evaluation. It means at the moment you applied sqrt to number eg. sqrt(2). It has already lost its symbolic meaning and replaced with real number.
To get what you need, you can redefine you function to work on string instead so that python interpreter won't try to evaluate it to number.
s1 = "-{b}+sqrt({d})/2*{a}".format(b=b,d=d,a=a)
s2 = "-{b}-sqrt({d})/2*{a}".format(b=b,d=d,a=a)
The part of code above will produce a string in symbolic from instead of number.
Upvotes: 0
Reputation: 4866
You can make use of Sympy
module! It is made for things like this.
For your case, you can use sympy.sqrt
instead of cmath.sqrt
to get the square root representation. Example:
import sympy
sympy.sqrt(8) # Output: 2*sqrt(2)
sympy.sqrt(8) * sympy.sqrt(3) # Output: 2*sqrt(6)
Here you can find an introduction to the module.
Upvotes: 3
Reputation: 630
Please have a look at symbolic computation with https://en.wikipedia.org/wiki/SymPy .
Upvotes: 1