When I encounter this type of problem I try to rewrite my function as an array of real and imaginary parts. For example, if f
is your function which takes complex input array x
(say x
has size 2, for simplicity)
from numpy
import *
def f(x):
# Takes a complex - valued vector of size 2 and outputs a complex - valued vector of size 2
return [x[0] - 3 * x[1] + 1 j + 2, x[0] + x[1]] # < --
for example
def real_f(x1):
# converts a real - valued vector of size 4 to a complex - valued vector of size 2
# outputs a real - valued vector of size 4
x = [x1[0] + 1 j * x1[1], x1[2] + 1 j * x1[3]]
actual_f = f(x)
return [real(actual_f[0]), imag(actual_f[0]), real(actual_f[1]), imag(actual_f[1])]
Here append() and extend() methods can be used to make it automatic and easily extendable to N number of variables
def real_eqns(y1):
y = []
for i in range(N):
y.append(y1[2 * i + 0] + 1 j * y1[2 * i + 1])
real_eqns1 = eqns(y)
real_eqns = []
for i in range(N):
real_eqns.extend([real_eqns1[i].real, real_eqns1[i].imag])
return real_eqns
I have been testing an algorithm that has been published in literature that involves solving a set of 'm' non-linear equations in both Matlab and Python. The set of non-linear equations involves input variables that contain complex numbers, and therefore the resulting solutions should also be complex. As of now, I have been able to get pretty good results in Matlab by using the following lines of code:, 1 week ago This tutorial is an introduction to solving nonlinear equations with Python. The solution to linear equations is through matrix operations while sets of nonl... ,I was wondering if there is something I am applying incorrectly, and if anybody has an idea on maybe how to properly solve complex non-linear equations in Python. , 1 week ago Feb 17, 2014 · The set of non-linear equations involves input variables that contain complex numbers, and therefore the resulting solutions should also be complex. As of now, I have been able to get pretty good results in Matlab by using the following lines of code: lambdas0 = ones (1,m)*1e-5; options = optimset ('Algorithm','levenberg-marquardt',...
lambdas0 = ones(1, m) * 1e-5;
options = optimset('Algorithm', 'levenberg-marquardt', ...'MaxFunEvals', 1000000, 'MaxIter', 10000, 'TolX', 1e-20, ...'TolFun', 1e-20);
Eq = @(lambda) maxentfun(lambda, m, h, g);
[lambdasf] = fsolve(Eq, lambdas0, options);
from numpy
import * def f(x): # Takes a complex - valued vector of size 2 and outputs a complex - valued vector of size 2
return [x[0] - 3 * x[1] + 1 j + 2, x[0] + x[1]] # < --
for example def real_f(x1): # converts a real - valued vector of size 4 to a complex - valued vector of size 2 # outputs a real - valued vector of size 4 x = [x1[0] + 1 j * x1[1], x1[2] + 1 j * x1[3]] actual_f = f(x) return [real(actual_f[0]), imag(actual_f[0]), real(actual_f[1]), imag(actual_f[1])]
lambdas0 = ones(1, m) * 1e-5;
options = optimset('Algorithm', 'levenberg-marquardt', ...'MaxFunEvals', 1000000, 'MaxIter', 10000, 'TolX', 1e-20, ...'TolFun', 1e-20);
Eq = @(lambda) maxentfun(lambda, m, h, g);
[lambdasf] = fsolve(Eq, lambdas0, options);
lambdas0 = np.ones(m) * 1e-5 sol = root(maxentfun, lambdas0, args = (m, h, g), method = 'lm', tol = 1e-20, options = {
'maxiter': 10000,
'xtol': 1e-20
}) lambdasf = sol.x
minpack.error: Result from
function call is not a proper array of floats.
from numpy
import * def f(x): # Takes a complex - valued vector of size 2 and outputs a complex - valued vector of size 2
return [x[0] - 3 * x[1] + 1 j + 2, x[0] + x[1]] # < --
for example def real_f(x1): # converts a real - valued vector of size 4 to a complex - valued vector of size 2 # outputs a real - valued vector of size 4 x = [x1[0] + 1 j * x1[1], x1[2] + 1 j * x1[3]] actual_f = f(x) return [real(actual_f[0]), imag(actual_f[0]), real(actual_f[1]), imag(actual_f[1])]
In this section we investigate different methods for solving for the roots (i.e. zeros) of a nonlinear equations with a single independent variable.,The bisection method, sometimes called the binary search method, is a simple method for finding the root, or zero, of a nonlinear equation with one unknown variable. (If the equation is linear, we can solve for the root algebraically.),Hybrid methods simply combine two or more root finding methods to create a robust algorithm. For example, Brent's Method uses the Bisection Method to get near the root, then the Secant Method is used to polish it off for faster convergence.,Other stopping procedures can be applied at Step 6 in the previous pseudocode. For example, we can select a tolerance of $\epsilon$ and generate $p_1, p_2, \ldots, p_N$ until one of the following conditions is met
def bisection(f, a, b, max_iterations = 10000, tolerence = 1e-6):
FA = f(a)
for i in range(max_iterations):
p = a + (b - a) / 2
FP = f(p)
if np.isclose(FP, 0.0) or(b - a) / 2 < tolerence:
return p
if np.sign(FA) * np.sign(FP) > 0:
a = p
FA = FP
else:
b = p
return
f = lambda x: x ** 2.0 - 25 fprime = lambda x: 2 * x x0 = 6 x0 - f(x0) / fprime(x0)
5.083333333333333
fig, ax = plt.subplots(figsize = (8, 6))
ax.spines["left"].set_position("zero")
ax.spines["right"].set_color("none")
ax.yaxis.tick_left()
ax.spines["bottom"].set_position("zero")
ax.spines["top"].set_color("none")
ax.xaxis.tick_bottom()
ax.set_xlim(-0.0, 10.0)
ax.set_ylim(-60, 60)
x = np.linspace(-1, 10.0, 100)
ax.plot(x, f(x), "k-")
ax.plot(x, fprime(x0) * (x - x0) + f(x0), "r-")
ax.text(9, 40, r "$f^\prime\left(x_0\right)$")
ax.text(8, 48, r "$f\left(x\right)$")
plt.show()
p = [0.4]
f = lambda x: np.cos(x) - x ** 3
if x is not None
else None
fprime = lambda x: -3 * x ** 2 - np.sin(x) if x is not None
else None
for i in range(15):
x = p[-1]
if p[-1] is not None
else p[-2]
xold = x
x = x - f(x) / fprime(x)
p.append(None)
p.append(x)
if np.abs(x - xold) < 1e-4:
break
count = 0
subcount = 0
p_label = []
for _ in range(len(p)):
p_label.append(r "$p_{}$".format(count))
subcount += 1
if subcount == 2:
subcount = 0
count += 1
fig, ax = plt.subplots(figsize = (8, 6))
ax.spines["left"].set_position("zero")
ax.spines["right"].set_color("none")
ax.yaxis.tick_left()
ax.spines["bottom"].set_position("zero")
ax.spines["top"].set_color("none")
ax.xaxis.tick_bottom()
ax.set_xlim(-0.2, 2.0)
ax.set_ylim(-4, 4)
x = np.linspace(-1, 3, 100)
lines = []
lines.append(ax.plot(x, f(x), "k-", label = r "$\cos(x) - x^3$")[0])
lines.append(ax.plot([], [], "k--")[0])
lines.append(ax.plot([], [], "r-")[0])
lines.append(ax.text([], [], "", fontsize = 10))
def animate(i):
lines[1].set_data([p[i], p[i]], [0.0, f(p[i])])
if p[i] is None:
lines[2].set_data(x, fprime(p[i - 1]) * (x - p[i - 1]) + f(p[i - 1]))
lines[3].set_text("")
if p[i] is not None:
if f(p[i]) > 0:
lines[3].set_y(f(p[i]) + 0.2)
lines[3].set_x(p[i] - 0.05)
lines[3].set_text(p_label[i])
else:
lines[3].set_y(f(p[i]) - 0.2)
lines[3].set_x(p[i] - 0.05)
lines[3].set_text(p_label[i])
return
plt.close("all")
ani2 = FuncAnimation(fig, animate, frames = len(p), interval = 1600)
ani2
The solution of a set of nonlinear equations,Find a solution of a system of nonlinear equations.,The functions in the second part of this module are designed to solve a set of nonlinear equations in n unknowns,An approximation to the error in the solution x is given by e where e is the solution to the set of linear equations
>>> from math
import exp
>>>
f = lambda x: x - exp(-x)
>>> x = 1.
>>> from naginterfaces.library
import roots
>>>
soln = roots.contfn_brent_interval(x, f)
>>> print('Final value of x is {:1.8f}.'.format(soln.x))
Final value of x is 0.56714329. >>>
print(
...'Search interval was [' +
...', '.join(['{:1.8f}'] * 2).format(soln.a, soln.b) +
...'].'
...)
Search interval was[0.50000000, 0.90000000].
>>> x = 0.6 >>> soln = roots.contfn_cntin(x, f)
>>> print('Final value of x is {:1.8f}.'.format(soln))
Final value of x is 0.56714329.
The new function, real_f can be used in fsolve: the real and imaginary parts of the function are simultaneously solved for, treating the real and imaginary parts of the input argument as independent. ,When I encounter this type of problem I try to rewrite my function as an array of real and imaginary parts. For example, if f is your function which takes complex input array x (say x has size 2, for simplicity)
When I encounter this type of problem I try to rewrite my function as an array of real and imaginary parts. For example, if f
is your function which takes complex input array x
(say x
has size 2, for simplicity)
from numpy
import *
def f(x):
# Takes a complex - valued vector of size 2 and outputs a complex - valued vector of size 2
return [x[0] - 3 * x[1] + 1 j + 2, x[0] + x[1]] # < --
for example
def real_f(x1):
# converts a real - valued vector of size 4 to a complex - valued vector of size 2
# outputs a real - valued vector of size 4
x = [x1[0] + 1 j * x1[1], x1[2] + 1 j * x1[3]]
actual_f = f(x)
return [real(actual_f[0]), imag(actual_f[0]), real(actual_f[1]), imag(actual_f[1])]