How to pythonically tuple quantities and physical units?

Now, when the question is how to parse a string for a quantity and a physical unit , the next question: what is the best way to continue to collect these two on the one hand, does not cost too much performance, but, on the other hand, adds a unit check.

To understand what I mean, take two speeds v = 5 m/sand as an example u = 10 mph. the previous question is already converting everything into SI units (so you won \ 't because of this one more Mars mission came out ). Thus, internally it would be possible, for example, a tuple v = (5, m/s)and u = (4.4704, m/s), and the output procedure would take care to use the preferred units for output. When applying single operations on two, for example, the addition or subtraction of their squares are valid, others, like v - 1/u, are complete and complete meaningless. But how is this best implemented? Some features that I have been considering so far:

  • Not. Since only internal SI units are used, it may be obvious which units are used. But neglecting this information is likely to become a source of error if the formulas become more complex.
  • Subclass tupleand override all valid operations pending unit consistency checks. Sounds fun...
  • Save the values ​​as sympy.core.mul.Multimes a (significant function) sympy.physics.unit.Unit, for example v = 5*unit.m/unit.s. I do not expect much performance, plus I still have to check if the result of the operation remains in the form magnitude * unit.
  • Use numpy.arraywith an extra record sympy.physics.unit.Unitthat already performs basic operations. This will still require manual verification of device integrity (it may also be necessary to process the fact that, for example, m+m=2m...)
  • numpy.array tuple, , super - . , __getattribute__ , , ...

/pythonic? ? , , ?

edit , ; , (, sympy.Symbol s)

+5
1

Magnitude:

from magnitude import mg

m = mg(5, 'kg')
a = mg(9.82, 'm/s2')
f = m * a
print f, f == mg(49.1, 'N')

u = mg(70, 'km/h')
g = mg(9.82, 'm/s2')
s = (u**2) / (2*g)
print s, s > mg(10, 'm')

, :

>>> m = mg(5, 'kg')
>>> a = mg(9.82, 'm/s')
>>> f = m * a
>>> print f, f == mg(49.1, 'N')
MagnitudeError: Incompatible units in comparison: [1, -2, 0, 1, 0, 0, 0, 0, 0] and [1, -1, 0, 1, 0, 0, 0, 0, 0]

, , .

+1

All Articles