2

I try to write a script that simulates a resistor. It takes 2 arguments for example P and R and it should calculate all missing values of this resistor. The problem is that I don't want to write every single possible equation for every value. This means I want to write something like (U=RxI, R=U/R, I=U/R , P=UxI) and the script should then complete all equation with the given values for every equation.

For example, something like this:

in R=10
in I=5
out U=R*I
out P=I**2 * R
John Ingram
  • 164
  • 1
  • 12
minestone
  • 76
  • 5
  • I'm not sure that you can avoid writing all functions... you maybe can but using some symbolic library, i think it's not a good idea.. – Ulises Bussi Nov 09 '21 at 16:04
  • 1
    You can write generic function that accepts those inputs and calculates the missing parameters/values. Required values can be passed as Null so you can find those Null values inside function body – Shedrack Nov 09 '21 at 16:09

2 Answers2

2

In vanilla python, there is no solution as general as the one you are looking for.

The typical solution would be to write an algorithm for every option (only given U, only given R) and then logically select which option to execute.

You may also want to consider using a module like SymPy, which has a solver module that may be more up your alley.

John Ingram
  • 164
  • 1
  • 12
2

You can use https://pypi.org/project/Equation/ Packages.

Example

>>> from Equation import Expression
>>> fn = Expression("sin(x+y^2)",["y","x"])
>>> fn
sin((x + (y ^ (2+0j))))
>>> print fn
\sin\left(\left(x + y^{(2+0j)}\right)\right)
>>> fn(3,4)
(0.42016703682664092+0j)

Sympy

Second: https://github.com/sympy/sympy/wiki

  • Arbitrary precision integers, rationals and floats, as well as symbolic expressions
  • Simplification (e.g. ( abb + 2bab ) → (3ab^2)), expansion (e.g. ((a+b)^2) → (a^2 + 2ab + b^2)), and other methods of rewriting expressions
  • Functions (exp, log, sin, ...)
  • Complex numbers (like exp(Ix).expand(complex=True) → cos(x)+Isin(x))
  • Taylor (Laurent) series and limits
  • Differentiation and integration
Mani
  • 280
  • 1
  • 10