0

Equation

Let's say we have the following equation:

E = Q / P

From that, we also have the following two equations:

Q = E * p
P = Q / E

So, given two of the three variables, we can find the other variable.

Class representation

Here's a class that we can use to model this equation:

class EQP:

    # E = Q / P

    E_ = None
    Q_ = None
    P_ = None
       
    def P(self): return self.Q() / self.E() if self.P_ is None   and   self.Q_ is not None   and   self.E_ is not None else self.P_
    def Q(self): return self.E() * self.P() if self.Q_ is None   and   self.E_ is not None   and   self.P_ is not None else self.Q_
    def E(self): return self.Q() / self.P() if self.E_ is None   and   self.Q_ is not None   and   self.P_ is not None else self.E_
        
    def set_E(self, E): self.E_ = E; return self
    def set_Q(self, Q): self.Q_ = Q; return self
    def set_P(self, P): self.P_ = P; return self
    
    def __repr__(self) -> str:
        return f"<EQP E:{self.E()} Q:{self.Q()} P:{self.P()}>"

Solve for Q:

>>> EQP().set_E(-0.1).set_P(20)
<EQP E:-0.1 Q:-2.0 P:20>

Questions

Is this a good "Pythonic" API for equations?

Is there a better approach?

dharmatech
  • 8,979
  • 8
  • 42
  • 88
  • I suspect you are looking for [sympy](https://www.sympy.org) – 0x263A Jul 13 '22 at 04:20
  • Does this answer your question? [Simplest way to solve mathematical equations in Python](https://stackoverflow.com/questions/1642357/simplest-way-to-solve-mathematical-equations-in-python) – 0x263A Jul 13 '22 at 04:21
  • @0x263A, with sympy, I'd have to specify the equation each time. I'm looking for a good way to encapsulate the equation and have a clean API in front of it so the user is only concerned with providing the variables. I'm not opposed to using sympy in the implementation, but it seems like a class of some sort is the way to go to wrap the equation semantics. – dharmatech Jul 13 '22 at 04:32

0 Answers0