3

I am trying to ask for a float variable, then assign its scientific notation to it and then use that notation in the following operations. As in, I want the program to actually work with the notation, not just return the results in it. I managed to convert variable by using the print function:

def estim(abs(x)):
    a=print("{:.3e}".format(x))
    return a

However that does not actually assign the scientific value to x. I then tried

b=float(a)

but a is None type, so it doesn't work. Any help?

Edit: by scientific notation I mean X.YYYe+Z, example: 31234.34234 -> 3.12e+04

6
  • Well, your code makes no sense. Maybe, a="{:.3e}".format(x) will work? Commented Jan 29, 2015 at 19:40
  • In Python floats don’t internally work using “decimal notation” or “scientific notation.” These are only output formats. What do you mean by “work with the notation”? Commented Jan 29, 2015 at 19:42
  • I meant that instead of understading 44432.12, the program would consider it as 4.44*10^4, for instance, so actually 44400. @ForceBru ' s suggestion seems to work, thank you. Commented Jan 29, 2015 at 19:46
  • @L.R. 31234.34234 -> 3.12e+04 ... You need a="{:.2e}".format(x) and not a="{:.3e}".format(x). (Now don't edit) Commented Jan 29, 2015 at 19:49
  • What is it you want to do with this number? Scientific notation is a means of displaying a number. It doesn't change what the number is. So it only makes sense to "work with the number in scientific notation" if what you really want is to work with a string representation of it. Commented Jan 29, 2015 at 19:52

3 Answers 3

3

You need to use a="{:.3e}".format(x)

Here is an example

x=246789;
a="{:.3e}".format(x);
print a;
print float(a);

Output

2.468e+05
246800.0
Sign up to request clarification or add additional context in comments.

Comments

1

If you do "{:.3e}".format(x) you will get 3 digits after decimal, that is

>>> a = 31234.34234
>>> "{:.3e}".format(a)
'3.123e+04'

To get what you want, you need to do "{:.2e}".format(x).

>>> "{:.2e}".format(a)
'3.12e+04'
>>> float("{:.2e}".format(a))
31200.0

Converting it back to float will give you the original value

As a function

def estim(x):
    x = abs(x)
    a=("{:.2e}".format(x))
    print(a)
    return a

Tip:

You can use % (It might be deprecated)

>>> a = 31234.34234
>>> "%e"%a
'3.123434e+04'

1 Comment

The code for the estim function you gave does not work: “SyntaxError: invalid syntax.”
1

The returned value from a print is always None I suspect what you need is more along the lines of:

def estim(x):
    a="{:.3e}".format(abs(x))
    print a
    return a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.