简体   繁体   English

python是否可以为工程目的使用基于后缀的数字表示法?

[英]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. 作为一名电气工程师,我(我们?)使用python来帮助计算/自动化等。

When dealing with calculations using some real-world numbers it is VERY common to think in -nano, -pico, -tera , etc. way. 当使用一些真实数字处理计算时,以-nano,-pico,-tera等方式思考是非常常见的。

For example: I know what a 1pF capacitor is, but 1e-12 F capacitor is somewhow less friendly. 例如:我知道1pF电容器是什么,但是1e-12 F电容器是不太友好的。 Also, it is 4x more typing ( 1p vs 1e-12 ) and more error prone. 此外,它的输入次数增加了4倍( 1p vs 1e-12 )并且更容易出错。 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?): 所以问题是:是否有可能在python中运行(IPython?):

L = 1n
C = 1p
f = 1/(2*pi*sqrt(L*C))
print(f) gives: 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...) 所以不要在乎它是法拉或千克,而是关心后缀(-n,-u,-m,-M,-G ......)

Sure. 当然。 Just write your own parser and generate your own AST with Python's language services . 只需编写自己的解析器,并使用Python的语言服务生成自己的AST。

You could create a module with all the necessary units as symbols, say units.py, containing something like 您可以创建一个模块,其中包含所有必需的单位作为符号,例如units.py,其中包含类似的内容

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 那么在代码中,Farads中的50pF就是

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 . pyparsing附带的示例包括一个简单的表达式解析器,称为fourFn.py I adapted it to accept your suffixed literals with about 8 lines of additional code, find it here . 我修改它接受你的后缀文字与大约8行额外的代码,在这里找到它。 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. 此更改支持标准后缀 ,但1e1的“da”除外,因为我仅限于使用单个字符,而是使用“D”代替。

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. 如果你想把它变成一个交互式计算器,你可以使用我对fourFn.py所做的相同更改来调整Steven Siew的提交

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM