Why does exponential notation with decimal values fail? [closed]

∥☆過路亽.° 提交于 2019-12-01 21:46:33

问题


Conventionally 1e3 means 10**3.

>>> 1e3
1000.0
>>> 10**3
1000

Similar case is exp(3) compared to e**3.

>>> exp(3)
20.085536923187668
>>> e**3
20.085536923187664

However now notice if the exponent is a float value:

>>> exp(3.1)
22.197951281441636
>>> e**3.1
22.197951281441632

which is fine. Now for the first example:

>>> 1e3.1
  File "<stdin>", line 1
    1e3.1
        ^
SyntaxError: invalid syntax
>>> 10**3.1
1258.9254117941675

which shows Python does not like 1e3.1, Fortran too. Regardless it could be a standard (!) why it is like that?


回答1:


The notation with the e is a numeric literal, part of the lexical syntax of many programming languages, based on standard form/scientific notation.

The purpose of this notation is to allow you to specify very large/small numbers by shifting the point position. It's not intended to allow you to encode multiplication by some arbitrary power of 10 into numeric literals. Therefore, that point and the following digits aren't even recognised as part of the numeric literal token.

If you want arbitrary powers, as you've found, there are math functions and operators that do the job. Unlike a numeric literal, you even get to determine the parameter values at run-time.




回答2:


You seem to be conflating syntax for literals with operators. While you can claim that 1e3.1 follows your "convention" it should be quite clear that 1e3.1 is not a valid literal expression to the Python interpeter. The language has a defined standard grammar, and that grammer doesn't support floating point literal expressions as "exponents" for its numeric literals.

The "e" in a Python numeric literal is not an operator (any more than the decimal point would be). So your expectation that Python's literal syntax should support some "convention" ... based on some pattern you've divined ... is not particularly reasonable.




回答3:


From the docs:

sign           ::=  '+' | '-'
digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
indicator      ::=  'e' | 'E'
digits         ::=  digit [digit]...
decimal-part   ::=  digits '.' [digits] | ['.'] digits
exponent-part  ::=  indicator [sign] digits            #no dots allowed here  


来源:https://stackoverflow.com/questions/16493830/why-does-exponential-notation-with-decimal-values-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!