NEMM2020
NEMM2020

Reputation: 129

Rearranging and solving an equation in Python

I have the following velocity equation and I want to solve for position. I want Python to define a new equation so that position = (Velocity + 100) / 0.1.

However, if I change the velocity equation then I would also have to change the position equation. This is time consuming and I just want Python to solve for position automatically.

position = np.arange(-10000, 10001) # An array of integers from -10,000 to 10,000
Velocity = -100 + 0.1 * position # Equation
position = (Velocity + 100) / 0.1

Upvotes: 1

Views: 2538

Answers (1)

Matt Hall
Matt Hall

Reputation: 8152

Rearranging equations needs symbolic math. You need SymPy for that.

For example, define the symbols (usually these are single characters, not words):

>>> import numpy as np
>>> import sympy
>>> v, p = sympy.symbols('v p')

Now you can make an expression for v:

>>> vexpr = -100 + p / 10

And you can define an equation to solve:

>>> veq = sympy.Eq(v, vexpr)
>>> sympy.pprint(veq)
    p       
v = ── - 100
    10      
>>> pexpr, = sympy.solve(veq, p)
>>> pexpr
10*v + 1000

And you can turn your expression into a Python function, which will work on your position array:

>>> f = sympy.lambdify(p, vexpr)
>>> position = np.arange(-10000, 10001)
>>> f(position)
array([-1100. , -1099.9, -1099.8, ...,   899.8,   899.9,   900. ])

You can change your expression for v and re-solve or re-compute these other things.

Upvotes: 3

Related Questions