Thursday, February 12, 2009

Convert number to scientific notation

Here's a snip to convert a number to scientific notation in Python:

def convertToScientific(nr):
coefficient = float(nr)
exponent = 0
while abs(coefficient) >= 10:
exponent += 1
coefficient = coefficient / 10
while abs(coefficient) < 1:
exponent -= 1
coefficient = coefficient * 10
return (coefficient, exponent)

No comments: