Could python have suffix-based number notation for engineering purposes?
As an electrical engineer I (we?) use python for helping out with calculation/automation/etc.
When dealing with calculations using some real-world numbers it is VERY common to think in -nano, -pico, -tera, etc. way.
For example: I know what a 1pF capacitor is, but 1e-12 F capacitor is somewhow less friendly. Also, it is 4x more typing (1p vs 1e-12) and more error prone. Not to say that when displaying numbers, having suffixed number is simply easier.
So the question is: is it possible to have this working in python (IPython?):
L = 1n
C = 1p
f = 1/(2*pi*sqrt(L*C))
print(f) 开发者_如何学Cgives: 5.033G (or whatever the accuracy should be)
It would be incredibly useful also as just a calculator!
Thanks.
UPDATE: What I look for is not units handling, but just suffixed numbers handling. So don't care whether it's a farad or a kilogram, but DO care about the suffix (-n,-u,-m,-M,-G...)
Sure. Just write your own parser and generate your own AST with Python's language services.
You could create a module with all the necessary units as symbols, say units.py, containing something like
pico = 1*e-12
nano = 1*e-9
micro = 1*e-6
mili = 1*e-3
Farad = 1
pF = pico*Farad
nF = nano*Farad
then in code, 50pF in Farads is
units
50*units.pF
Does not make much sense to introduce complexity in the language for something that can be simply be solved with proper naming and functions:
L_nano = unit_nano(1)
C_pico = unit_pico(1)
f = 1/(2*pi*sqrt(L*C))
print(to_Giga(f)) gives: 5.033G
The examples that come with pyparsing include a simple expression parser, called fourFn.py. I adapted it to accept your suffixed literals with about 8 lines of additional code, find it here. This change supports the standard suffixes, with the exception of "da" for 1e1, since I was limited to using single characters, I used "D" instead.
If you want to make this into an interactive calculator, you can adapt Steven Siew's submission using the same changes I made to fourFn.py.
精彩评论