Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

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  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top