Consider following equation system:
1623.66790917 * x ** 2 + 468.829686367 * x * y + 252.762128419 * y ** 2 + -1027209.42116 * x + -301192.975791 * y + 188804356.212 = 0
11154.1759415 * x ** 2 + 31741.0229155 * x * y + 32933.5622632 * y ** 2 + -16226174.4037 * x + -26323622.7497 * y + 6038609721.67 = 0
As you see there are two pairs of complex solutions to the system. I tried sympy but it was not a success. I want to know how to figure it out in Python. BTW I don't have a nice initial guess to use numeric methods.
You can solve those equations numerically using mpmath's findroot(). As far as I know there isn't a way to tell findroot() to find multiple roots, but we can get around that restriction: first, find a solution pair (xa, ya), then divide the equations by (x - xa)*(y - ya). You do have to supply an initial approximate solution, but I managed to find something that worked in only a few tries.
from mpmath import mp
mp.dps = 30
prec = 20
f_1 = lambda x, y: 1623.66790917 * x ** 2 + 468.829686367 * x * y + 252.762128419 * y ** 2 + -1027209.42116 * x + -301192.975791 * y + 188804356.212
f_2 = lambda x, y: 11154.1759415 * x ** 2 + 31741.0229155 * x * y + 32933.5622632 * y ** 2 + -16226174.4037 * x + -26323622.7497 * y + 6038609721.67
def solve(f1, f2, initxy):
return mp.findroot([f1, f2], initxy, solver='muller')
def show(x, y):
print 'x=', mp.nstr(x, prec)
print 'y=', mp.nstr(y, prec)
print mp.nstr(f_1(x, y), prec)
print mp.nstr(f_2(x, y), prec)
print
f1a = f_1
f2a = f_2
xa, ya = solve(f1a, f2a, (240+40j, 265-85j))
show(xa, ya)
f1b = lambda x, y: f1a(x, y) / ((x - xa) * (y - ya))
f2b = lambda x, y: f2a(x, y) / ((x - xa) * (y - ya))
xb, yb = solve(f1b, f2b, (290+20j, 270+30j))
show(xb, yb)
output
x= (246.82064795986653023 + 42.076841530787279711j)
y= (261.83565021239842638 - 81.555049135736951496j)
(0.0 + 3.3087224502121106995e-24j)
(0.0 + 0.0j)
x= (289.31873055121622967 + 20.548128321524345062j)
y= (272.23440694481666637 + 29.381152413744722108j)
(0.0 + 3.3087224502121106995e-24j)
(0.0 + 0.0j)
Related
Trying to replace the function U2(x,y,z) with specified values of x,y,z. Not sure how to do that with sympy because they are as "x = arange.(-h,h,0.001)" as seen in the code below.
Below you will find my implementation with sympy. Additionally I am using PyCharm.
This implementation is based on Dr. Annabestani and Dr. Naghavis' paper: A 3D analytical ion transport model for ionic polymer metal composite actuators in large bending deformations
import sympy as sp
h = 0.1 # [mm] half of thickness
W: float = 6 # [mm] width
L: float = 28 # [mm] length
F: float = 96458 # [C/mol] Faraday's constant
k_e = 1.34E-6 # [F/m]
Y = 5.71E8 # [Pa]
d = 1.03 - 11 # [m^2/s] diffiusitivity coefficient
T = 293 # [K]
C_minus = 1200 # [mol/m^3] Cation concentration
C_plus = 1200 # [mol/m^3] anion concentration
R = 8.3143 # [J/mol*K] Gas constant
Vol = 2*h*W*L
#dVol = diff(Vol,x) + diff(Vol, y) + diff(Vol, z) # change in Volume
theta = 1 / W
x, y, z, m, n, p, t = sp.symbols('x y z m n p t')
V_1 = 0.5 * sp.sin(2 * sp.pi * t) # Voltage as a function of time
k_f = 0.5
t_f = 44
k_g = 4.5
t_g = 0.07
B_mnp = 0.003
b_mnp: float = B_mnp
gamma_hat_2 = 0.04
gamma_hat_5 = 0.03
gamma_hat_6 = 5E-3
r_M = 0.15 # membrane resistance
r_ew = 0.175 # transverse resistance of electrode
r_el = 0.11 # longitudinal resistance of electrode
mu = 2.4
sigma_not = 0.1
a_L: float = 1.0 # distrubuted surface attentuation
r_hat = sp.sqrt(r_M ** 2 + r_ew ** 2 + r_el ** 2)
lambda_1 = 0.0001
dVol = 1
K = (F ** 2 * C_minus * d * (1 - C_minus * dVol)) / (R * T * k_e) # also K = a
K_hat = (K-lambda_1)/d
gamma_1 = 1.0
gamma_2 = 1.0
gamma_3 = 1.0
gamma_4 = 1.0
gamma_5 = 1.0
gamma_6 = 1.0
gamma_7 = 1.0
small_gamma_1 = 1.0
small_gamma_2 = 1.0
small_gamma_3 = 1.0
psi = gamma_1*x + gamma_2*y + gamma_3*z + gamma_4*x*y + gamma_5*x*z + gamma_6*y*z + gamma_7*x*y*z + (small_gamma_1/2)*x**2 + (small_gamma_2/2)*y**2 + (small_gamma_3/2)*x*z**2
psi_hat_part = ((sp.sin(((m + 1) * sp.pi) / 2 * h)) * x) * ((sp.sin(((n + 1) * sp.pi) / W)) * y) * ((sp.sin(((p + 1) * sp.pi) / L)) * z)
psi_hat = psi * psi_hat_part # Eqn. 19
print(psi_hat)
x1: float = -h
x2: float = h
y1: float = 0
y2: float = W
z1: float = 0
z2: float = L
I = psi_hat.integrate((x, x1, x2), (y, y1, y2), (z, z1, z2)) # Integration for a_mnp Eqn. 18
A_mnp = ((8 * K_hat) / (2 * h * W * L)) * I
Partial = A_mnp * ((sp.sin(((m + 1) * sp.pi) / 2 * h)) * x) * ((sp.sin(((n + 1) * sp.pi) / W)) * y) * ((sp.sin(((p + 1) * sp.pi) / L)) * z)
start = Partial.integrate((p, 0 , 10E9), (n, 0, 10E9), (m, 0, 10E9)) #when using infinity it goes weird, also integrating leads to higher thresholds than summation
a_mnp_denom = (((sp.sin(((m + 1) * sp.pi) / 2 * h)) ** 2) * ((sp.sin(((n + 1) * sp.pi) / W)) ** 2) * (
(sp.sin(((p + 1) * sp.pi) / L)) ** 2) + K_hat)
a_mnp = A_mnp / a_mnp_denom # Eqn. 18
U2 = sp.Function("U2")
U2 = a_mnp * ((sp.sin(((m + 1) * sp.pi) / 2 * h)) * x) * ((sp.sin(((n + 1) * sp.pi) / W)) * y) * (
(sp.sin(((p + 1) * sp.pi) / L)) * z) # Eqn. 13
x = np.arange(-h, h, 0.001)
y = np.arange(-h, h, 0.001)
z = np.arange(-h, h, 0.001)
f= sp.subs((U2), (x ,y ,z))
I currently get the error message: ValueError: subs accepts either 1 or 2 arguments. So that means I can't use the subs() method and replace() also doesn't work too well. Are there any other methods one can use?
Any help will be grateful, thank you!
Oscar is right: you are trying to deal with too much of the problem at once. That aside, Numpy and SymPy do not work like you think they do. What were you hoping to see when you replaced 3 variables, each with a range?
You cannot replace a SymPy variable/Symbol with a Numpy arange object, but you can replace a Symbol with a single value:
>>> from sympy.abc import x, y
>>> a = 1.0
>>> u = x + y + a
>>> u.subs(x, 1)
y + 2.0
>>> u.subs([(x,1), (y,2)])
4.0
You might iterate over the arange values, creating values of f and then doing something with each value:
f = lambda v: u.subs(dict(zip((x,y),v)))
for xi in range(1,3): # replace range with your arange call
for yi in range(-4,-2):
fi = f((xi,yi))
print(xi,yi,fi)
Be careful about iterating and using x or y as your loop variable, however, since that will then lose the assignment of the Symbol to that variable,
for x in range(2):
print(u.subs(x, x)) # no change and x is no longer a Symbol, it is now an int
I am writing a function to calculate three nonlinear equations. I have the function to calculate them, but the thing is I give initial guess to them - which works fine. But now I have a constraint for x between (1/4 and 1/3). For that, I am making 2 for lops. One is for ptinting 13 different values, the other one for the constraint.
However the code does not give me the result at all:
import numpy as np
import math
from scipy.optimize import fsolve
def equations(vars):
x, y, z = vars
eq1 = ((x / (1 - x)) - (((2.5*np.cos(z)) / (8 * np.pi * np.sin(z) ** 2)) * (1 + (design_ratio * np.tan(z)))))
eq2 = ((y / (1 + y)) - (2.5 / (8 * np.pi * np.cos(z))) * (1 -design_ratio *( (1 / np.tan(z)))))
eq3 = np.tan(z) - ((1-x) /( 1.40 * (1+y)))
return [eq1, eq2, eq3]
n=13
for i in range(0, n):
for j in range(25555, 33333):
x = 0.00001 *x
x, y, z = fsolve(equations, (0.328, 0.048, 28))
print(x, y, z)
Frankly, using a loop is a terrible approach to handle the box constraint 1/4 <= x <= 1/3. Since fsolve doesn't support (box) constraints, you can rewrite the problem
Solve F(x,y,z) = 0 with 1/4 <= x <= 1/3
as an equivalent minimization problem
min np.sum(F(x,y,z)**2) s.t. 1/4 <= x <= 1/3
and solve it by means of scipy.optimize.minimize like this:
import numpy as np
from scipy.optimize import minimize
def F(vars):
x, y, z = vars
eq1 = ((x / (1 - x)) - (((2.5*np.cos(z)) / (8 * np.pi * np.sin(z) ** 2)) * (1 + (design_ratio * np.tan(z)))))
eq2 = ((y / (1 + y)) - (2.5 / (8 * np.pi * np.cos(z))) * (1 -design_ratio *( (1 / np.tan(z)))))
eq3 = np.tan(z) - ((1-x) /( 1.40 * (1+y)))
return np.array([eq1, eq2, eq3])
bounds = [(1./4, 1./3), (None, None), (None, None)]
res = minimize(lambda vars: np.sum(F(vars)**2), x0=(0.328, 0.048, 28), bounds=bounds)
I have a polynomial: eps * x3 - x2 + 2 + 3 * x * eps-2.
How can I get a list of all coefficients including negative?
I have tried coeffs() and all_coeffs() methods but they do not work with negative powers of epsilon:
import sympy as sp
x, eps = sp.symbols('x E')
expr = eps * x**3 - x**2 + 2 + 3 * x * eps**(-2)
coeffs_list = sp.Poly(expr, eps).coeffs()
I want to get list of coefficients like [x^3, x^2 + 2, 3*x]
If you are not sure what the negative power of eps is you can find the coefficients of the expression when put over a common denominator:
>>> n, d expr.as_numer_denom()
>>> Poly(n, eps).coeffs()
[x**3, 2 - x**2, 3*x]
Multiplying with a large power of eps helps to get the coeffients.
import sympy as sp
x, eps = sp.symbols('x E')
expr = eps * x**3 - x**2 + 2 + 3 * x * eps**(-2)
coeffs_list = sp.Poly(expr*eps**2, eps).coeffs()
gives
[x**3, 2 - x**2, 3*x]
Right now, I am working on something (in Python) to create an ellipse and display it on the screen (in the console). I have the ellipse creation already, but rotating the ellipse gives me problems.
Ellipse Method:
def ellipse(yc, xc, b, a, rotation=0):
yc_min_b = yc - b
# divide b to account for spacing in console
b = int(round(b / 2 + 0.01)) - 1
yc = yc_min_b + b
points = []
a2 = a*a
b2 = b*b
fa2 = 4 * a2
fb2 = 4 * b2
x = 0
y = b
sigma = 2 * b2 + a2 * (1 - 2 * b)
while b2 * x <= a2 * y:
points.append((xc + x, yc + y))
points.append((xc - x, yc + y))
points.append((xc + x, yc - y))
points.append((xc - x, yc - y))
if sigma >= 0:
sigma += fa2 * (1 - y)
y -= 1
sigma += b2 * ((4 * x) + 6)
x += 1 # INCREMENT
x = a
y = 0
sigma = 2 * a2 + b2 * (1 - 2 * a)
while a2 * y <= b2 * x:
points.append((xc + x, yc + y))
points.append((xc - x, yc + y))
points.append((xc + x, yc - y))
points.append((xc - x, yc - y))
if sigma >= 0:
sigma += fb2 * (1 - x)
x -= 1
sigma += a2 * ((4 * y) + 6)
y += 1 # INCREMENT
# now rotate points
sin = math.sin(rotation)
cos = math.cos(rotation)
rotated = []
for point in points:
x = point[0]
y = point[1]
'''
px -= xc
py -= yc
xnew = px * c - py * s
ynew = px * s + py * c
px = xnew + xc
py = ynew + yc
'''
#XRot := Round(XCenter + (X - XCenter) * CAngle - (Y - YCenter) * SAngle);
#YRot := Round(YCenter + (X - XCenter) * SAngle + (Y - YCenter) * CAngle);
x = round(xc + (x + xc) * cos - (y - yc) * sin)
y = round(yc + (x - xc) * sin + (y - yc) * cos)
rotated.append((int(x), int(y)))
points = rotated
print points
ell_matr = []
# set up empty matrix
maxx = 0
maxy = 0
for point in points:
y = point[1]
x = point[0]
if y > maxy:
maxy = y
if x > maxx:
maxx = x
for i in range(maxy + 1):
ell_matr.append([])
for j in range(maxx + 1):
ell_matr[i].append(' ')
for point in points:
y = point[1]
x = point[0]
ell_matr[y][x] = fill
return ell_matr
I would ignore the matrix part, as it is translating the points into a matrix to display on screen.
Here is the output of an ellipse without rotation.
And when I add a 45 degree rotation (converted to radians)
Is there a better way to rotate the points?
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
# Prototype of N-R for a system of two non-linear equations
#evaluating functions of two variables
# f(x,y)=1.6 * x ** 2 + 3.6 * x * y - 7.8 * x - 2.6 * y + 5.2
# g(x,y)=0.9 * y ** 2 + 3.1 * x **2 - 6.2 * x + 6.2 * y
# x = 0.5
# y =0.4
from math import *
eq1 = raw_input('Enter the equation 1: ')
eq2 = raw_input('Enter the equation 2: ')
x0 = float(input('Enter x: '))
y0 = float(input('Enter y: '))
def f(x,y):
return eval(eq1)
def g(x,y):
return eval(eq2)
Ea_X = 1
x = x0
y = y0
for n in range(1, 8):
a = (f(x + 1e-06, y) - f(x,y)) / 1e-06 #in this one start the trouble
b = (f(x, y + 1e-06) - f(x,y)) / 1e-06
c = 0 - f(x,y)
d = (g(x + 1e-06, y) - g(x,y)) / 1e-06
eE = (g(x, y + 1e-06) - g(x,y)) / 1e-06
f = 0 - g(x,y)
print "f(x, y)= ", eq1
print "g(x, y)= ", eq2
print """x y """
print x, y
print """a b c d e f """
print a, b, c, d, e, f
print """
a * x + b * y = c
d * x + e * y = f
"""
print a," * x + ",b," * y = ",c
print d," * x + ",eE," * y = ",f
_Sy = (c - a * f / d) / (b - a * eE / d)
_Sx = (f / d) - (eE / d) * _Sy
Ea_X = (_Sx ** 2 + _Sy ** 2)**0.5
x = x + _Sx
y = y + _Sy
print "Sx = ", _Sx
print "Sy = ", _Sy
print "x = ", x
print "y = ", y
print "|X_1 - X_0| = ", Ea_X
I've been testing the Newton-Rapson method for two non-linear equations,
the prototype code works but then I was thinking in making it more
useful, because the prototype is about the input of the 2 equations
and the first guesses, and it would be good to implement a for loop
instead of starting the process like 6 or 10 to resolve just one
of the so many equations that I'm working with
# Prototype of N-R for a system of two non-linear equations
# f(x,y)=1.6 * x ** 2 + 3.6 * x * y - 7.8 * x - 2.6 * y + 5.2
# g(x,y)=0.9 * y ** 2 + 3.1 * x **2 - 6.2 * x + 6.2 * y
# x = 0.5
# y =0.4
# evaluating functions of two variables
from math import *
eq1 = raw_input('Enter the equation 1: ')
eq2 = raw_input('Enter the equation 2: ')
x0 = float(input('Enter x: '))
y0 = float(input('Enter y: '))
def f(x,y):
return eval(eq1)
def g(x,y):
return eval(eq2)
Ea_X = 1
x = x0
y = y0
a = (f(x + 1e-06, y) - f(x,y)) / 1e-06
b = (f(x, y + 1e-06) - f(x,y)) / 1e-06
c = 0 - f(x,y)
d = (g(x + 1e-06, y) - g(x,y)) / 1e-06
eE = (g(x, y + 1e-06) - g(x,y)) / 1e-06
f = 0 - g(x,y)
print "f(x, y)= ", eq1
print "g(x, y)= ", eq2
print """x y """
print x, y
print """a b c d e f """
print a, b, c, d, e, f
print """
a * x + b * y = c
d * x + e * y = f
"""
print a," * x + ",b," * y = ",c
print d," * x + ",eE," * y = ",f
_Sy = (c - a * f / d) / (b - a * eE / d)
_Sx = (f / d) - (eE / d) * _Sy
Ea_X = (_Sx ** 2 + _Sy ** 2)**0.5
x = x + _Sx
y = y + _Sy
print "Sx = ", _Sx
print "Sy = ", _Sy
print "x = ", x
print "y = ", y
print "|X_1 - X_0| = ", Ea_X
In the line
f = 0 - g(x,y)
you assign a number to the name f. Since functions and other variables share a namespace in Python (a function is just a callable object, bound to any variable), this makes future iterations fail. Pick another name for the value you're assigning in the above line.
Here is the problem:
f = 0 - g(x,y)
You are rebinding f from a function to a float.