Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>Units</h2> <p>A solution would be to gather all units from the SymPy <code>units</code> module and use them to substitute the symbols created by <code>sympify</code></p> <pre><code>&gt;&gt;&gt; import sympy.physics.units as u ... subs = {} ... for k, v in u.__dict__.items(): ... if isinstance(v, Expr) and v.has(u.Unit): ... subs[Symbol(k)] = v # Map the `Symbol` for a unit to the unit &gt;&gt;&gt; # sympify returns `Symbol`s, `subs` maps them to `Unit`s &gt;&gt;&gt; print sympify('yard*millimeter/ly').subs(subs) 127*m/1313990343414000000000 </code></pre> <p>If the symbol is not in <code>units</code> it will just be printed as unknown symbol (for instance <code>barn</code>)</p> <pre><code>&gt;&gt;&gt; print sympify('barn/meter**2').subs(subs) barn/m**2 </code></pre> <p>But you can always add stuff to the <code>subs</code> dictionary.</p> <pre><code>&gt;&gt;&gt; subs[Symbol('almost_meter')] = 0.9*u.meter ... sympify('almost_meter').subs(subs) 0.9*m </code></pre> <p>SI prefixes don't work exactly like you want them. You will need to add a multiplication sign (or hope that it is a common unit like <code>km</code> which is explicitly implemented). Moreover, as they are not <code>Unit</code> instances but rather <code>Integer</code> instance you will have to add them to <code>subs</code>:</p> <pre><code>&gt;&gt;&gt; import sympy.physics.units as u ... subs = {} ... for k, v in u.__dict__.items(): ... if (isinstance(v, Expr) and v.has(u.Unit)) or isinstance(v, Integer): ... subs[Symbol(k)] = v &gt;&gt;&gt; print sympify('mega*m').subs(subs) 1000000*m </code></pre> <p>For unicode you might need some preprocessing. I do not think SymPy makes any promises about unicode support.</p> <p>If you implement new <code>Unit</code>s, please consider making a pull request with them on github. The file to edit should be <code>sympy/physics/units.py</code>.</p> <h2>Whitespaces and implicit multiplication</h2> <p>In the dev version of SymPy you can find code for assuming implicit multiplications where appropriate whitespaces are written:</p> <pre><code>&gt;&gt;&gt; from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_multiplication_application) &gt;&gt;&gt; parse_expr("10sin**2 x**2 + 3xyz + tan theta", ... transformations=(standard_transformations + ... (implicit_multiplication_application,))) 3*x*y*z + 10*sin(x**2)**2 + tan(theta) </code></pre> <h2>Security</h2> <p><code>sympify</code> uses <code>eval</code> which is exploitable if you are going to use it for a web facing app!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload