Can Sympy identify functions in expressions, if fuctions are defined? - python

I've seen that Sympy has a sympy.Function feature, but can't find an answer to the following in the documentation.
Is it possible to find custom functions in expressions and use the function definition to simplify them.
As a very simple example, I define the function: f(x) = 2 * exp(x).
Now let's say I have some Sympy expression: 6 * exp(y + z)
Is it possible to tell Sympy to simplify this expression to give a result in terms of the function f.... i.e. so the output from Sympy is: 3 * f(x).
I've found that using .subs() works for simple substitution of variables, but this doesn't seem to work for functions that contain symbols as arguments, as above.
Thanks.

I think what you want to do is not supported by Sympy at the moment (see for instance this stackoverflow question). Nevertheless, something very close can be done with this code:
from sympy import symbols, exp
x, f = symbols('x, f')
expr = 6 * exp(x)
f_func = 2 * exp(x)
print(expr.subs({f_func: f}))
# 3 * f
In the above code I have assumed that the expression you wanted to simplify (expr in the code) was a function of x.

Related

How to solve equations in python

I try to write a script that simulates a resistor. It takes 2 arguments for example P and R and it should calculate all missing values of this resistor.
The problem is that I don't want to write every single possible equation for every value. This means I want to write something like (U=RxI, R=U/R, I=U/R , P=UxI) and the script should then complete all equation with the given values for every equation.
For example, something like this:
in R=10
in I=5
out U=R*I
out P=I**2 * R
You can use https://pypi.org/project/Equation/ Packages.
Example
>>> from Equation import Expression
>>> fn = Expression("sin(x+y^2)",["y","x"])
>>> fn
sin((x + (y ^ (2+0j))))
>>> print fn
\sin\left(\left(x + y^{(2+0j)}\right)\right)
>>> fn(3,4)
(0.42016703682664092+0j)
Sympy
Second: https://github.com/sympy/sympy/wiki
Arbitrary precision integers, rationals and floats, as well as symbolic expressions
Simplification (e.g. ( abb + 2bab ) → (3ab^2)), expansion (e.g. ((a+b)^2) → (a^2 + 2ab + b^2)), and other methods of rewriting expressions
Functions (exp, log, sin, ...)
Complex numbers (like exp(Ix).expand(complex=True) → cos(x)+Isin(x))
Taylor (Laurent) series and limits
Differentiation and integration
In vanilla python, there is no solution as general as the one you are looking for.
The typical solution would be to write an algorithm for every option (only given U, only given R) and then logically select which option to execute.
You may also want to consider using a module like SymPy, which has a solver module that may be more up your alley.

Export cubic equation formulas to code in Python

I'm writing code for the method to solve this cubic equation. I use python's math library.
(float)(-b+pow(pow(b,3)-27*pow(a,2)*d,1/3))/3*a;
(float)((math.sqrt(delta))/(3*a))*((pow(abs(k)+math.sqrt(pow(k,2)+1),1/3))+(pow(abs(k)-math.sqrt(pow(k,2)+1),1/3)))-(b/(3*a));
Below are pictures of 2 math formulas I need to solve:
A few comments to begin with:
/3*a at the end of your first line does not do what you think it does. Use parentheses!! Parentheses are important. Write / (3 * a) instead.
It's mostly a matter of style, but personally I think A**B is easier to read than pow(A, B) (they are equivalent, as you can see in the documentation).
Note that your code will require b, a, d, Delta and k to be already-existing variables with already-given values. One way to get around that is to encapsulate your code into a function, with these four variables as arguments of the function. Another way to get around that is to use the symbolic expression library sympy.
With these comments in mind, here are two ways to rewrite your first expression and use it in python code. I will let you adapt the second expression yourself.
First way: encapsulating in a function with arguments
def expr1(a,b,d):
numerator = - b + (b**3 - 27*a*a*d)**(1/3)
denominator = 3 * a
return numerator / denominator
print(expr1(2,7,3))
# -0.7219330585463425
Second way: using sympy
Sympy is a library for symbolic calculus. This means we can use it to define symbols, which are basically variables without a value, and then ask it to remember expressions that use these symbols. We are going to use the function sympy.symbols to define our symbols, and expr.subs to evaluate an expression expr by giving values to those symbols. I encourage you to read sympy's documentation.
import sympy
a, b, d = sympy.symbols('a b d')
numerator = - b + (b**3 - 27*a*a*d) ** (1/3)
denominator = 3 * a
expr1 = numerator / denominator
print(expr1)
# (-b + (-27*a**2*d + b**3)**0.333333333333333)/(3*a)
print(expr1.subs([(a,2), (b,7), (d,3)]))
# -0.721933058546343

Python-How to do Algebraic Math with Exponents and Square Roots

so I am having issues trying to do basic math in Python. I can do basic math, but when I add in exponents, square roots, etc, I have errors with the IDE. How do I do this?
Here are a few of my problems that I am having issues with:
(n(n-1))/2)
(4)* pi * r ** 2=
(r(cos(a)**2) + r(sin(b))**2)**(.5)
((y**2) - (y**1))/((x**2) - (x**1))=
(n*(n-1))/2 should work if you have already given n a numeric value (e.g. n=2 or something). Your original expression has unbalanced parentheses (three closing parens and only two opening parens) and it is missing the multiplication sign (*) which is necessary in python, otherwise n(n-1) would be interpreted as the function n supplied with the input n-1, in which case you get a message like "TypeError: 'int' object is not callable", assuming you had previously defined n=2 or the like. It's telling you that the integer n cannot be called like a function, which is how it interprets n().
To get pi (3.14159...) in python, you should import the math package and then use math.pi like this:
import math
r = 2
x = 4*math.pi*r**2
You don't need parentheses around the 4. Parentheses are used for grouping, when you need operations to be done in a different order than the standard order of operations. You don't need the trailing equal sign (that's a syntax error).
In the third expression you are using implicit multiplication notation which is fine for pencil and paper but in python you need to use * every time you multiply. Also, you need to import the math package and then use math.sin and math.cos.
import math
a = 90
b = 45
x = (r*(math.cos(a)**2) + r*(math.sin(b))**2)**(.5)
There doesn't appear to be anything wrong with the last expression except the trailing = sign which should be removed. Store the result of this expression in a variable if you want to keep it for future use:
z = ((y**2) - (y**1))/((x**2) - (x**1))
If you just type the expression at the command line it will print the result immediately:
x = 3
y = 2
((y**2) - (y**1))/((x**2) - (x**1))
but if you are using this expression in a script you want to save the result in a variable so you can use it later or print it out or something:
z = ((y**2) - (y**1))/((x**2) - (x**1))
As was previously pointed out in the comments, x**1 is the same, mathematically, as x so it's not clear why you would want to write it this way, but it's not wrong.
You can use math.pow() or the simpler ** syntax:
There are two ways to complete basic maths equations in python either:
use the ** syntax. e.g:
>>> 2 ** 4
16
>>> 3 ** 3
27
or use math.pow(). e.g:
>>> import math
>>> math.pow(5, 2)
25.0
>>> math.pow(36, 0.5)
6.0
As you can see, with both of these functions you can use any real power so negative for inverse or decimals for roots.
In general, for these types of equations, you want to look into the math module. It has lost of useful functions and defined constants that you may find useful. In particular for your specific problems: math.pi and these trig. functions.
I hope these examples and the links I made are useful for you :)

Trigonometric identities with Python and Sympy, tan(A/2) = (sin A )/(1 + cos A)

I'm not sure how to get Sympy to perform / simplify these types of identities?
It does things like sin(a + b), but doesn't seem to do others (like the one in the title)
One approach is to try various combinations of simplification functions/methods such as rewrite and simplify. For example, the following gives the result you want:
import sympy as sp
x = sp.var('x', real = True)
f = sp.tan(x/2)
sp.re(f.rewrite(sp.exp).simplify().rewrite(sp.sin)).simplify()
sin(x)/(cos(x) + 1)

input a symbolic function in a python code

I was just wondering if there is a method to input a symbolic function in a python code?
like in my code I have:
from sympy import *
import numpy as np
import math
myfunction = input("enter your function \n")
l = Symbol('l')
print myfunction(l**2).diff(l)
If I put cos, sin or exp, as an input then I have an output of: -2*l*sin(l**2)
What If I want to make the input function more general, say a polynomial or a complex function, or maybe a function of combined cos, sin and exp ???
As a syntax, sin + cos simply isn't going to work very well. The simplest way to get the general case to work is to give sympy an expression to evaluate. We can let sympify do the hard work of turning a string into a sympy object:
>>> s = raw_input("enter a formula: ")
enter a formula: sin(x) + x**3
>>> s
'sin(x) + x**3'
>>> f = sympy.sympify(s)
>>> f
x**3 + sin(x)
After which we can substitute and evaluate:
>>> f.subs({'x': 2})
sin(2) + 8
>>> f.subs({'x': 2}).evalf()
8.90929742682568
See also my answer here for some other tricks you can pull with a bit of work:
>>> f = definition_to_function("f(x) = sin(x) + x**3")
>>> f(3)
27.14112000805987
If you need good support for symbolic funcions, you should consider using sage.
It is a preprocessor for python, with lots of math support including symbolic functions. Sage code can be intermixed with normal python-code.
The package is quite big, but I have good experiences with it. It is free and open-source.

Categories