Last active
September 3, 2021 18:51
-
-
Save tcibinan/8b7b58c6861a03752f8ec309e809d770 to your computer and use it in GitHub Desktop.
Find extremum of a function using sympy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sympy.solvers import solve | |
from sympy.abc import x | |
def getDeepDotQuality(func, arg, val, n = 3): | |
dy = func.diff(arg) | |
dyn = dy.subs(arg, val) | |
if (dyn == 0): | |
return getDeepDotQuality(dy, arg, val, n+1) | |
elif (n % 2 == 1): | |
return 'has an inflection point' | |
elif (dyn > 0): | |
return 'is min' | |
else: | |
return 'is max' | |
return 'aaaaaa' | |
def getDotQuality(func, arg, val): | |
dy = func.subs(arg, val) | |
if (dy > 0): | |
return 'is min' | |
elif (dy < 0): | |
return 'is max' | |
else: | |
return getDeepDotQuality(func, arg, val) | |
def findExtremums(func, arg): | |
dy = func.diff(arg) | |
ddy = dy.diff(arg) | |
extremums = solve(dy, arg) | |
for val in extremums: | |
print('%s %s for x=%s' % (func, getDotQuality(ddy, arg, val), val)) | |
return | |
findExtremums(x**2, x) | |
findExtremums(x**3 - 2*x**2 + x + 1, x) | |
findExtremums(2*x**4, x) | |
findExtremums(2*x**3, x) |
@JensKue I'm so glad that it helped you! sympy is such a powerful tool yet pretty difficult to use.
Very useful, thanks. However, this may not work with some functions such as rationals
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much this code really helped me. :D
Just one think I had to use sympy.solveset() instead of sympy.solve() in line 29