-2

Is it possible to calculate a square root of an expression in python ? For example , the square root of: (a^4 - 8a^2 -16a + 16)?

Of course the result will be with a, not a numeric value. I read about math.sqrt() and tried doing this , but pycharm insisted that i would assign a value into a .

import math
a = 16
b = math.sqrt(a**4 - 8*(a**2) -16*a +16 )
print b

this code works , but I do not want to assign into a , I want an expression as a result .

Noam
  • 96
  • 1
  • 12

2 Answers2

3

Okay, I'm assuming that what you want is to take an algebraic expression, and simplify it by factoring parts of it. Is that right?

You could use sympy for this general class of question, but I note that (to the best of my knowledge) your example doesn't have a simpler answer! Here's an example where it can work:

>>> from sympy import Symbol, factor
>>> a = Symbol("a")
>>> factor(a**4 - 8*a**3 + 20*a**2 - 16*a + 4)
(a**2 - 4*a + 2)**2

However, I don't think your example has any factors. Is it actually an instance of a problem you need to solve, or just a general example of the shape of the problem?

Weeble
  • 17,058
  • 3
  • 60
  • 75
0

Python has a lot of batteries inside, however its huge standard library does not contain any symbolic algebraic module. Thus, if you want to do symbolic calculations, you have to use external modules, such as SymPy (as already suggested), or mathematical systems, such as SageMath.

What you can do in "standard" Python is to define a function which takes a as a parameter and that returns the corresponding value of your expression:

def f(a):
    import math
    return math.sqrt(a**4 - 8*(a**2) -16*a +16)

Depending on your application, this could be enough.

davidedb
  • 867
  • 5
  • 12