2

I have been playing around with equations for electric systems using Sympy, and have already manage quite a lot so that equation look nice and decent : all values hold units which are following them even trough combinations of equations. That's quite important I think, because the aim is that the document I am writing to calculate my values IS the final document I will present (I'm using Jupyter notebooks and will PDF the whole thing).

Now come my problem : somehow, sympy decided that % are not a unit by itself (true enough, it has no dimension) and that it makes no sense to show it - at all. It seems to even parse my self declared units to remove any percent character that could appears ...

As long as I agree that % have no dimension, the character still exist for a reason - if it was that useless, it would have not existed to begin with. Humans like to read percents with a nice % at the end, because it already indicate that the result has been multiplied by a factor of 100. It also make the result more readable.

In code :

# imports
import sympy as sp
from sympy import init_printing
init_printing(use_latex=True)
init_printing(use_latex='mathjax')
import sympy.physics.units as u
from IPython.display import display

#define unit
percent = u.Unit('ab%c', 'ab%c')*100 # a,b and c are only there for debug. Only % is needed

#define dummy equation
Error_= sp.symbols('Error')
total_error = 1 # error is not yet in %. 1 means 100%
Eq = sp.Eq(Error_, total_error*percent) 
display(Eq)

result : Error=100ab

Why is everything after the % plainly removed ? I've even been careful not to import all units in the global namespace so if % were to be detected, wouldn't it need u.% ?

PS: I have a long history of 3 days (total) working with Python. I'm usually more of a C guy. Hope I've not missed a stupid error.

user
  • 5,370
  • 8
  • 47
  • 75
Mr Buisson
  • 127
  • 7

1 Answers1

3

This works for me:

percent = u.Unit('percent', r'\%') * 100

Most probably % have to be escaped as it has to be escaped in LaTeX as well.

Ilya V. Schurov
  • 7,687
  • 2
  • 40
  • 78
  • You are welcome :) Note that `u.percent` also exists, but its meaning is opposite: it is equal to 1/100 (which is in fact what `u.percent` should mean: `25 * percent == 0.25`). – Ilya V. Schurov Dec 11 '16 at 19:30