Scientific notation literal with variable exponent in Python

Viewed 666

The literal 3e4 represents the float 30000 in python (3.8 at least).

>>> print(3e4)
30000.0

The syntax of the following code is clearly invalid:

x=4
3ex

3ex is not a valid expression, but the example helps me ask my question:

Clearly, the expression 3*10**4 represents the same number, but my question here is purely related to the scientific notation literals. Just for my curiosity, is there a way to use the same syntax with a variable power, better than:

x=4
eval(f"1e{x}")

One subtle difference between 3e4 and 3*10**4 is the type (float and int respectively). Is there also a difference in execution time perhaps in calculating these two expressions?

1 Answers

To your first question: No, the documentation does not suggest you can.

Is there a way to use the same syntax with a variable power?

When float is instantiated from a string, it calls out to a CPython C library PyOS_string_to_double to which handles making the str locale-aware (. vs ,) before passing the string directly to the C function strtod doc.

Meanwhile the documentation for PyOS_string_to_double does not mention of any special way to configure the exponent.

To your second question about performance, this is easily benchmarked. But, we do not have a candidate to benchmark against. So, this is a moot question.

Is there also a difference in execution time perhaps?

I hope this satiates your curiosity. If not, feel free to dig into the C code that I linked.

Related