I have been trying to locate a method similar to Excel's Solver where I can target a specific value for a function to converge on. I do not want a minimum or maximum optimization.
For example, if my function is:
f(x) = A^2 + cos(B) - sqrt(C)
I want f(x) = 1.86, is there a Python method that can iterate a solution for A, B, and C to get as close to 1.86 as possible? (given an acceptable error to target value?)
You need a root finding algorithm for your problem. Only a small transformation required. Find roots for g(x):
g(x) = A^2 + cos(B) - sqrt(C) - 1.86
Using scipy.optimize.root, Refer documentation:
import numpy as np
from scipy import optimize
# extra two 0's as dummy equations as root solves a system of equations
# rather than single multivariate equation
def func(x): # A,B,C represented by x ndarray
return [np.square(x[0]) + np.cos(x[1]) - np.sqrt(x[2]) - 1.86, 0, 0]
result = optimize.root(func , x0 = [0.1,0.1,0.1])
x = result.x
A, B, C = x
x
# array([ 1.09328544, -0.37977694, 0.06970678])
you can now check your solution:
np.square(x[0]) + np.cos(x[1]) - np.sqrt(x[2])
# 1.8600000000000005
Related
First off, thank you in advance for bearing with my novice understanding of Python. I am coming from MATLAB so hopefully that gives some context.
In MATLAB I define a mathematical function as:
f =# (x) 2*x(1)^2 + 4*x(2)^3
In Python, I wrote:
def f(x):
return 2*x(1)**2 + 4*x(2)**3
But I get an error inside my other function (finite difference method for creating gradient vector):
line 9, in f
return 2*x(1)**2 + 4*x(2)**3
TypeError: 'numpy.ndarray' object is not callable
(an input X1 that contains n-number of entries, specified by the number of variables in the original equation, is fed back into the function f(x) to evaluate at a specific point).
Update 2021-10-22
Below I have included the code for reference. THIS CODE CURRENTLY WORKS.
The main thing I am wondering is how I can create an arbitrary number of variables for an equation like I do in MATLAB with x(1),x(2)...x(n). I have been told I should use def f(*x) but when I add the '*' operator on f(x) I get a tuple index out of range error.
import math, numpy as np
def gradFD(var_init,fun,hx):
df = np.zeros((len(var_init),1)) #create column vector for gradient output
# Loops each dimension of the objective function
for i in range(0,len(var_init)):
x1 = np.zeros(len(var_init)) #initialize x1 vector
x2 = np.zeros(len(var_init))
x1[i] = var_init[i] - hx
x2[i] = var_init[i] + hx
z1 = fun(x1)
z2 = fun(x2)
# Calculate Slope
df[[i],[0]] = (z2 - z1)/(2*hx)
# Outputs:
c = df #gradient column vector
return c
And the test script:
import math
import numpy as np
from gradFD import gradFD
def f(x):
return 2*x[0]**2 + 4*x[1]**3 #THIS IS THE NOW WORKING CODE
#return 2*x**2 + 4*y**3
var_init = [1,1] #point to evaluate equation at
c = gradFD(var_init,f,1e-3)
print(c)
Array indexing in Python is done with square brackets, not parentheses. And remember that Python starts in indices at 0, not 1.
def f(x):
return 2*x[0]**2 + 4*x[1]**3
Your function is called f but you are trying to call x(2). You get the error because you are trying to call x as a function, but x is a numpy array
I have a function [ -4*x/sqrt(1 - (1 - 2*x^2)^2) + 2/sqrt(1 - x^2) ] that I need to evaluate at x=0. However, whenever you graph this function, for some interval of y there are many y-values at x=0. This leads me to think that the (subs) command can only return one y-value. Any help or elaboration on this? Thank you!
Here's my code if it might help:
x = symbols('x')
f = 2*asin(x) # f(x) function
g = acos(1-2*x**2) # g(x) function
eq = diff(f-g) # evaluating the derivative of f(x) - g(x)
eq.subs(x, 0) # substituting 0 for x in the derivative of f(x) - g(x)
After I run the code, it returns NaN, which I assume is because substituting in 0 for x returns not a single number, but a range of numbers.
Here is the graph of the function to be evaluated at x=0:
You should always give SymPy as many assumptions as possible. For example, it can't pull an x**2 out of a sqrt because it thinks x is complex.
A factorization an then a simplification solves the problem. SymPy can't do L'Hopital on eq = A + B since it does not know that both A and B converge. So you have to guide it a little by bringing the fractions together and then simplifying:
from sympy import *
x = symbols('x', real=True)
f = 2*asin(x) # f(x) function
g = acos(1-2*x**2) # g(x) function
eq = diff(f-g) # evaluating the derivative of f(x) - g(x)
eq = simplify(factor(eq))
print(eq)
print(limit(eq, x, 0, "+"))
print(limit(eq, x, 0, "-"))
Outputs:
(-2*x + 2*Abs(x))/(sqrt(1 - x**2)*Abs(x))
0
4
simplify, factor and expand do wonders.
I want to take the derivative of a multivariable function using SymPy and then for a) the symbolic result to be printed and then b) the result of the derivative at a point to be printed. I'm using the following code
import math as m
import numpy
import scipy
#define constants
lambdasq = 0.09
Ca = 3
qOsq = 2
def f1(a,b,NN,ktsq,x):
return NN*x**(-a)*ktsq**b*m.exp(m.sqrt(16*Ca/9*m.log(1/x)*m.log((m.log(ktsq/lambdasq))/m.log(qOsq/lambdasq))))
from sympy import *
x = symbols('x')
def f2(NN,a,b,x,ktsq):
return -x*diff(m.log(f1),x)
This runs but I can't find a way to get the symbolic result to be printed and when I try to evaluate at a point, say e.g adding in print(f2(0.3,0.1,-0.2,0.1,3)) I get an error
TypeError: must be real number, not function
When I replace f1 with its symbolic representation, I get instead the error
ValueError:
Can't calculate 1st derivative wrt 0.100000000000000.
So I can summarise my question as follows
a) How to print out a symbolic derivative and its value at a point when I call diff(m.log(f1),x) (i.e without having to replace f1 by its actual representation)
b) If I have to use the symbolic representation in the differentiation (i.e use diff(m.log(NN*x**(-a)*ktsq**b*m.exp(m.sqrt(16*Ca/9*m.log(1/x)*m.log((m.log(ktsq\
/lambdasq))/m.log(qOsq/lambdasq))))),x) then how to print out the symbolic derivative and its value at a point?
New to Python so hopefully there is a relatively simple fix.
Thanks!
I'm posting this answer since this thread is #1 on my search engine when searching for 'simpy multivariate differentiation' and might help someone.
example 1
import sympy as sp
def f(u):
return (u[0]**2 + u[1]**10 + u[2] - 4)**2
u = sp.IndexedBase('u')
print(sp.diff(f(u), u[0]))
outputs
4*(u[0]**2 + u[1]**10 + u[2] - 4)*u[0]
This is the derivative of f(u) wrt u[0]
example 2
if we want the whole jacobian, we can do:
for i in range(3):
print(sp.diff(f(u), u[i]))
which outputs
4*(u[0]**2 + u[1]**10 + u[2] - 4)*u[0]
20*(u[0]**2 + u[1]**10 + u[2] - 4)*u[1]**9
2*u[0]**2 + 2*u[1]**10 + 2*u[2] - 8
we can define a temp function and copy paste these lines
def temp(u):
return np.array([
4*(u[0]**2 + u[1]**10 + u[2] - 4)*u[0],
20*(u[0]**2 + u[1]**10 + u[2] - 4)*u[1]**9,
2*u[0]**2 + 2*u[1]**10 + 2*u[2] - 8,
])
temp([1., 1., 1.])
this outputs array([ -4., -20., -2.])
and to verify
from autograd import grad
gradient = grad(f)
gradient([1., 1., 1.])
this outputs: [array(-4.), array(-20.), array(-2.)]
Note:This is just a simple showcase how you can do multivariate derivatives in sympy. I hope I can help someone with this
First, math functions are numeric, they cannot work with SymPy's symbols. Use the corresponding functions from SymPy (exp, log, sqrt) which you already imported with from sympy import *:
def f1(a, b, NN, ktsq, x):
return NN*x**(-a)*ktsq**b*exp(sqrt(16*Ca/9*log(1/x)*log((log(ktsq/lambdasq))/log(qOsq/lambdasq))))
Second, within f2 you are trying to differentiate f1. But f1 is a callable Python function, not a SymPy expression. You need to pass in some arguments to get a SymPy expression, which can then be differentiated.
def f2(NN, a, b, x0, ktsq):
return (-x*diff(log(f1(a, b, NN, ktsq, x)), x)).subs(x, x0)
Here the numeric arguments, except the value x0, are passed to f1, resulting in a SymPy expression containing x. That is a thing to be differentiated. After that, the numeric value x0 is substituted for x.
print(f2(0.3,0.1,-0.2,0.1,3)) # 0.366748952743614
A take-away point is that SymPy differentiates expressions, not functions. There is no concept of f' in SymPy, only f'(x).
Let us assume I have an ODE with x'(t) = f(x) with the respective solution x(t) = ϕ(x(0),t) of a initial condition x(0). Now I intend to calculate numerically the equilibria as a function of their initial condition: eq(x0) := ϕ(x0, ∞). The ODEs are such that these equilibria exist unambiguously for all initial conditions (including eq = ∞).
My poor man's approach would be to integrate the ODE up to a late time and fetch that value (for brevity I do not show the plotting):
import numpy as np
from scipy.integrate import odeint
# ODE
def func(X,t):
return [ X[2]**2 * (X[0] - X[1]),
X[2]**3 * (X[0] + 3 * X[1]),
-X[2]**2]
# Forming a grid
n = 15
x0 = x1 = np.linspace(0,1,n)
x0_,x1_ = np.meshgrid(x0,x1)
eq = np.zeros([n,n,3])
t = np.linspace(0,100,1000)
x2 = 1
for i in range(n):
for j in range(n):
X = odeint(func,[x0_[j,i],x1_[j,i],x2], t)
eq[j,i,:] = X[-1,:]
Naive example above:
The problem with that approach is that you can never be sure if it converged. I know that you can just find the roots of f(x), but this would not yield the equilibria as a function of their initial conditions (You could trace them back, but since this function is not injective, you will not find values for all initial values). I somehow need a ODE solver which integrates until an equilibria is reached (or stops integrating if it goes beyond a limit). Do you have any ideas?
I am dealing with a set of several non-linear equations that I was able to reduce analytically to set of two implicit equations with two variables. Now I wish to find roots of those equations using Brent's method. I would like to pass one function as an argument to another and solve the equation for variable 2 depending on every variable 1.
In mathematical terms I wish to solve: f(x,y) and g(x,y) in this way f(x,g(x)).
Simplify example of what I wish to do can be presented here.
Instead of:
import scipy.optimize
from scipy.optimize import fsolve
def equations(p):
y,z = p
f1 = -10*z + 4*y*z - 5*y + 4*z**2 - 7
f2 = 2*y*z + 5*y - 3
return (f1,f2)
and solve it by:
y, z = fsolve(equations,[0,19])
I wish to write something like that:
def func2(x, y):
f2= 2*y*x + 5*y - 3
return brentq(f2, -5, 5)
def func(x,y):
y = func2(x,y)
return -10*x + 4*x*y - 5*y + 4*x**2 - 7
sol, = brentq(lambda x: func(x, func2), -5, 5)
I wish to ask for help in how to pass a function as an argument for this particular purpose and explain what am I doing wrong. I am new to Python and maybe there is a better way to ensure precise solution to my problem.