Float to Scientific notation [duplicate] - python-2.7

I want to have Python2.7 print out floating point numbers in scientific notation, forced to start with 0. For instance, assume
a=1234567890e12
print '{:22.16E}'.format(a)
1.2345678900000000E+21
However, I want a print output that looks like:
0.1234567890000000E+22
Notice that the exponent is raised by one since the desired output is forced to a leading zero. How can I achieve this?
Thanks.

The fortranformat package will do what you are looking for.
import fortranformat as ff
a=1234567890e12
lineformat = ff.FortranRecordWriter('(1E26.16)')
lineformat.write([a])
Output:
' 0.1234567890000000E+22'

Handles E- as well.
def fortranFormat(n):
a = '{:.4E}'.format(float(n))
e = a.find('E')
return '0.{}{}{}{:02d}'.format(a[0],a[2:e],a[e:e+2],abs(int(a[e+1:])*1+1))
print(fortranFormat('60.505'))
print(fortranFormat('74.705'))
print(fortranFormat('2.000000E-09'))
output:
0.60505E+02
0.74705E+02
0.20000E-08

Well, since what you want to do is not "standard" scientific notation, I'm not sure if there is a simple call to do this. Here is a hack, however, that will work
a = 1234567890e12
A = str(a)
exp = A.find('e+')
converted = '0.' + A[0] + A[2:exp] + 'e+' + str(int(A[exp+2:])+1)

Related

Python - Rounding to two specific digits EXACTLY

The number I have = 52.003
The number I want = 52.00
The number I get after rounding to 2 decimal places:
round(52.003, 2)
>>> 52.0
How do I keep the second digit without Python automatically rounding it?
You can use the format() function in Python.
"{0:.2f}".format(round(52.003, 2))
You can also use the string formatting operator.
'%.2f' % 52.003
You can modify the output format like this:
a = 52.003
print "%.2f" % a
Try this function :
import numpy as np
Round = lambda x, n: eval('"%.' + str(int(n)) + 'f" % ' + repr(x))
a = Round(52.003,2)
print a
>>> 52.00
Just indicate the number of decimals you want as a kwarg. However the result will be a string.

Python code to convert decimal to binary

I need to write a Python script that will convert and number x in base 10 to binary with up to n values after the decimal point. And I can't just use bin(x)! Here's what I have:
def decimal_to_binary(x, n):
x = float(x)
test_str = str(x)
dec_at = test_str.find('.')
#This section will work with numbers in front of the decimal
p=0
binary_equivalent = [0]
c=0
for m in range(0,100):
if 2**m <= int(test_str[0:dec_at]):
c += 1
else:
break
for i in range(c, -1, -1):
if 2**i + p <= (int(test_str[0:dec_at])):
binary_equivalent.append(1)
p = p + 2**i
else:
binary_equivalent.append(0)
binary_equivalent.append('.')
#This section will work with numbers after the decimal
q=0
for j in range(-1, -n-1, -1):
if 2**j + q <= (int(test_str[dec_at+1:])):
binary_equivalent.append(1)
q = q + 2**j
else:
binary_equivalent.append(0)
print float((''.join(map(str, binary_equivalent))))
So say you call the function by decimal_to_binary(123.456, 4) it should convert 123.456 to binary with 4 places after the decimal, yielding 1111011.0111.
The first portion is fine - it will take the numbers in front of the decimal, in this case 123, and convert it to binary, outputting 1111011
However, the second portion, which deals with values after the decimal, is not doing what I think it should. The output it gives is not .0111, but rather .1111
I ran through the code with pen and paper writing down the value for each variable and it should work. But it doesn't. Can anyone help me fix this?
I call the function as decimal_to_binary(123.456, 4) and it prints out 1111011.1111
You're close, but there's an issue with your comparison when you go beyond the decimal:
if 2**j + q <= (int(test_str[dec_at+1:])):
What you're doing here is comparing a fractional value (since j is always negative) to a whole integer value. This comparison will, for all practical purposes, always be true.
Based on the surrounding logic, my guess would be that you're attempting to compare it to the actual decimal value here. Using your data, that would be 0.4 on the first iteration, so you expect the statement to be evaluated as:
0.5 <= 0.4
The actual comparison in your code is:
0.5 <= 4
There are two separate issues here:
You're taking all of the numbers after the decimal point, but not actually including the decimal point itself in your extraction. This is primarily why you are getting whole numbers in your test incorrectly. This is fixed simply by referencing test_str[dec_at:] rather than test_str[dec_at+1:]
You're casting to int. Even if you applied the change in the first point, your code would still not run correctly. However, in that case it would be because the cast would truncate the value down to 0 on every iteration. Cast to a float instead: float(test_str[dec_at:])
Your comparison line thus becomes if 2**j + q <= (float(test_str[dec_at:])):, which provides the correct output on my machine.
Note that floating point comparisons can be "finicky" in some situations, depending on rounding and the like. There are ways to mitigate this if needed.

Python arithmetic operation returns 0

read = True
while read:
my_input = int(raw_input())
print my_input
result = (1/6) * my_input * (my_input + 1) * (my_input +2)
if result == 0:
print ''
read = False
break
else:
print result
I wrote this little code snippet to solve 1 + (1+2) + (1+2+3+)... without looping over anything but the result is always 0 for some reason. I am using PyDev on Eclipse but I do not think that's even remotely the issue
Thank you
Multiplying by zero always results in zero.
>>> a = (1/6)
>>> print a
0
This is happening because Python is casting the resulting operation to integer.
In order to get a float result you can specify the values in decimal notation.
>>> a = 1.0/6.0
>>> print a
0.166666666667
Integer division.
When you divide (1/6) it comes out to 0 because of integer division.
When two ints are divided, they come out to the normal answer, minus anything after the decimal point.
For example, 1/4 would usually equal 0.25.
However, everything after the decimal point is dropped, so it comes out to 0.

atof only returns integers?

I've got a routine which gets numbers in the exponent format(e.g. 2,5E-02 or 4E+06) as a QString. When I print the values I always only get integers and when they are smaller then 1 I always get 0.
Does anyone know what I am doing wrong here?
(with the cout line I only wanted to test whether the QString::number() is ruining it for me)
here is a code snippet:
QStringList valPair;
value = atof(valPair[0].replace(",",".").toAscii());
value1 =atof(valPair[1].replace(",",".").toAscii());
strValue = "[" + QString::number(value) + ", " + QString::number(value1) + "]";
//cout<<value<<" "<<value1;
I'd appreciate any help!
EDIT: It was a Problem with variable declaration...
double value, value1;
Why are you doing all that work? Qt already has what you're looking for if you use QString::toDouble and QString::number(). If you set your locale manually before calling toDouble() then you can use the comma decimal notation without replacing anything.
You could also create a string template like QString("[%1,%2]") and then use the double version of QString::arg.
The conversion function doesn't support your locale, which uses comma as a decimal separator. Use 2.4e4 instead.

Formatting Output

I need to output numbers in scientific notation such that there is always a "0" before the decimal point.
e.g. For the number x = 134.87546, I need to produce the output
0.134875E03 NOT 1.348755E02
Does someone know how to do this?
Thanks in Advance --Shiraz.
int exp = (int)log10(input)+1;
double shifted = input / pow(10.0, exp);
printf("%fE%d", shifted, exp);
int exponent = floor(log10(num)) + 1;
Then just print "0.", the number without decimals, "E", then the exponent.
You may investigate using the Boost Format library which is a general output formatting library.