How to Solve Equations in Python

Solving non linear equations where equations are equals in python

Looks like you have a system of non-linear equations.
For the example you provided, the system has four equations for four unknowns

Sample Image

where u is vector of unknowns C1, C2, C3, X, and f is vector function with components

Sample Image

You need to google for solvers of nonlinear systems of equations (e.g. nonlinear rootfinding problem). For python there is scipy.optimize.root, for example. Also, you may be interested to read chapters 4.5 and 4.6 of Fundamentals of Numerical Computation to understand choice of the solver.

solve two simultaneous equations: one contains a Python function

You can directly calculate that point. We can implement a python version of the intermediate calculation for lat long.

Be aware this calculations assume the earth is a sphere, and takes the curve into account, i.e. this is not a Euclidean approximation like your original post.

Say we have two (lat,long) points A and B;

import numpy as np

A = (52.234869, 4.961132)
B = (46.491267, 26.994655)

EARTH_RADIUS = 6371.009

We can than calculate the intermediate point fraction f by taking 100/distance-between-a-b-in-km

from sklearn.neighbors import DistanceMetric
dist = DistanceMetric.get_metric('haversine')

point_1 = np.array([A])
point_2 = np.array([B])

delta = dist.pairwise(np.radians(point_1), np.radians(point_2) )[0][0]

f = 100 / (delta * EARTH_RADIUS)

phi_1, lambda_1 = np.radians(point_1)[0]
phi_2, lambda_2 = np.radians(point_2)[0]

a = np.sin((1-f) * delta) / np.sin(delta)
b = np.sin( f * delta) / np.sin(delta)

x = a * np.cos(phi_1) * np.cos(lambda_1) + b * np.cos(phi_2) * np.cos(lambda_2)
y = a * np.cos(phi_1) * np.sin(lambda_1) + b * np.cos(phi_2) * np.sin(lambda_2)

z = a * np.sin(phi_1) + b * np.sin(phi_2)
phi_n = np.arctan2(z, np.sqrt(x**2 + y**2) )
lambda_n = np.arctan2(y,x)

The point C, going from A to B, with 100 km distance from A, is than

C = np.degrees( phi_n ), np.degrees(lambda_n)

In this case

(52.02172458025681, 6.384361456573444)

Solve system of linear equations in Python

from sympy import *
# unkowns
i1, i2, u1, u2 = symbols("i1, i2, u1, u2")
# knows quantities
id2, zg, zl, A, B, C, D, Y = symbols("id_2, z_g, z_l, A, B, C, D, Y")

# define equations:
# one way to do that is to write them as:
# (Left Hand Side) - (Right Hand Side) = 0
eq1 = i1 - (id2 - u1/zg)
eq2 = i2 - ((C+D*Y)*u1 + D* i1)
eq3 = i2 - (u2/zl)
eq4 = u2 - ((A+B*Y)*u1 + B*i1)

# solve the system of equation
sol = solve([eq1, eq2, eq3, eq4], [i1, i2, u1, u2])
# retrieve the solution of u2
sol[u2]
# out: (A*D*id_2*z_g*z_l - B*C*id_2*z_g*z_l)/(A*z_g + B*Y*z_g - B - C*z_g*z_l - D*Y*z_g*z_l + D*z_l)


Related Topics



Leave a reply



Submit