How to round numbers - python

How would I be able to round numbers like these to two decimal places which are all stored in a variable which has been outputted by a web scraper:
4.7532
4.7294
4.7056
4.6822857142857
4.65868
4.63522
4.6119866666667
4.58898
4.566064
4.543216
I am new to python so i'm not sure. I'm using Python 2

Use the built-in function round(), example:
>>> round(4.7532,2)
4.75
>>> round(4.7294,2)
4.73

I think from what you say, you have a single string containing these numbers, and you want to print them out as 2dp formatted?
If so, the first thing to do is split the single string into an array, and convert to floating point numbers
numstr = """4.7532
4.7294
4.7056
4.6822857142857"""
nums = [float(x) for x in numstr.split("\n")]
This gives us an array of floating point python numbers
Now, we want to output them, having rounded. We can do that a few ways, the easiest is probably
for num in nums:
print "%0.2f" % num
That will loop over all your numbers, and print them out one per line, formatted to two decimal places

Related

Converting from three decimals places to two decimal places in a list

I have a list online= [204.945, 205.953, 346.457] and I want to only have the numbers in the list to two decimal places (one list rounded and one list not-rounded). So like this, online= [204.94, 205.95, 346.45] for the not rounded and like this online= [204.95, 205.95, 346.46] for the rounded.
I don't even know any code that makes this possible, so I don't really have a code to show my approach. I mean I did try to play around with int() but that seems to remove all the decimal places and just gives me an integer.
You can use round() along with map() and lambda
list(map(lambda x: round(x,2), online))
Or, List-Comprehension
[round(item,2) for item in online]
OUTPUT:
[204.94, 205.95, 346.46]
Following function will do that:
def to_2_decimals(l):
for i in range(len(l)):
l[i]=int(l[i]*100)/100
online= [204.945, 205.953, 346.457,0.0147932132,142314324.342545]
to_2_decimals(online)
print(online)
But know, that rounding doubles does not save memory. If you just want string representation of your list elements to be shorter then use:
print("{:.2f}".format(online[i]))

How to represent the number like '1.108779411784206406864790428E-69', between 0-1 in Python

I have a number that comes from Sigmoid function like '1.108779411784206406864790428E-69' but it's naturally should be between 0-1. How can I represent it in that way? Thanks
The number that you got is the scientific notation of this number: 0.0000000000000000000000000000000000000000000000000000000000000000000011087794117842064068647904281594
To get the number like that, you need to do this:
x = 1.108779411784206406864790428E-69
print("%.100f" % x)
"%.100f" is the string to format, where 100 is the number of floats you need to show.
You can use the format statement to print. The original value is a float. For the convenience of readability python prints in scientific notation since this is a very small number. You can print upto more decimal places.. I have printed upto 96 decimal places below.
>>> a=1.108779411784206406864790428E-69
>>> "{:.96f}".format(a)
'0.000000000000000000000000000000000000000000000000000000000000000000001108779411784206406864790428'
Hope this helps.

how to round up the number for array format in .txt output i n python

I am trying to extract my analysis result in .txt file. The results show as below :
-3.298409999999999854e+04 -3.298409999999999854e+04
-3.297840000000000146e+04 -3.297840000000000146e+04
Code:
anodeIdx = [10,20,30]
stressAnodeXX = [x for i,x in enumerate(stress_xx[0].Y) if i in anodeIdx]
stressAnodeYY = [x for i,x in enumerate(stress_yy[0].Y) if i in anodeIdx]
np.savetxt('Stress_strain_Anode.txt',np.c_[stressAnodeXX,stressAnodeYY])
I expected the result to be -32984.1 but the actual output is -3.2984099999e+4
To save the number in a specific way, you can use optional parameter fmt of np.savetxt(). Documentation
In your case:
np.savetxt('Stress_strain_Anode.txt',np.c_[stressAnodeXX,stressAnodeYY], fmt='%.1f')
f is specifier wihch saves the number as decimal floating point.
.1 Represents how many decimal numbers should be after the decimal point.
I think the problem here is not the numbers not being rounded, but not being appropiately formatted.
You could use the fmt keyword argument of numpy.savetxt to solve this. (numpy documentation):
np.savetxt('Stress_strain_Anode.txt', np.c_[stressAnodeXX,stressAnodeYY], fmt='%.1f')
Where '%.1f' is a format string which formats numbers with one decimal digit.
Your result is actually -32984.1. Float representation in binary code is not ideal so you see it in a bit confusing way. If you want, you can just round your result (but it is not needed):
np.round(your_result_number, decimals=1)
which will return:
-32984.1
More about your result:
-3.2984099999e+4 has two confusing parts:
099999 in the end of number
e+4 in the end of output
e+4 is a scientific notation of your number. It means: "multiply it to 10^4=10000. If you will do it, you will get 3.29841 * 10000 = 32984.1
099999... in the end of the number appears because computer tries to represent decimal float number in binary code, which leads to small "errors". So your result is actually -32984.1.

How to convert strings to numbers in python while preserving fractional parts

Here is example
In > int('1.5')
Out > 1
In > int('10.5')
Out > 10
But I want to keep values intact. How do you do it?
Integers are only numbers that have no decimals.
-4,-3,-2,-1,0,1,2,3,4,...,65535 etc...
Floating point numbers or Decimal numbers are allowed to represent fractions and more precise numbers
10.5, 4.9999999
If you want to take a string and get a numerical type for non-whole numbers, use float()
float('10.5')
Here is a very simple elementary school explanation of integers
Here is the python documentation of numerical types
foo = 10.5
foo2 = int(foo)
print foo, foo2
10.5, 10
Integer can one represent whole number.
If you have a known consistent number of digest after the the comma, I recommend multiplying the number by 10 to the power of X.
Or round the number to the nearest whole number

Python: indexing floats?

I have two sets of data that I am reading via nested for loops in Python. I need to match lines of the two different text files using a common number (time). In the two files, time is written differently (ex. 21:53:28.339 vs. 121082008.3399). I only need the last four digits of the times to match them up, for example from 21:53:28.339, I only need '8.339'. For the most part, indexing the number as a string works just fine (ex: timeList[nid][7:]), except for situations such as the numbers listed above, where python rounds .3399 to .34.
Is there a way for me to keep the numbers in float form and to select unrounded digits from the data?
Thanks!
edit - using Decimal exclusively - with full example
import decimal
def simplify(text):
# might be a : separated value
text = text.split(':')[-1]
# turn into decimal
number = decimal.Decimal(text)
# remove everything but the ones place and forwards
number = number - (number/10).quantize(1, rounding=decimal.ROUND_FLOOR) * 10
# truncate to the thousandths
return number.quantize(decimal.Decimal('.001'), rounding=decimal.ROUND_FLOOR)
a = '121082008.3399'
b = '21:53:28.339'
assert simplify(a) == simplify(b)
print simplify(a), '=', simplify(b)
Scott if you compare the numbers using strings then you don't need any floats and there will be no 'rounding' going on.
'8.339' == '8.339'
or, if you have
a = '8.3399'
b = '8.339'
then
a[:-1] == b
however if you do decide to work with them as 'numbers', then as Ignacio pointed out, you can use decimals.
from decimal import Decimal
number_a = Decimal(a[:-1])
number_b = Decimal(b)
now
number_a == number_b
Hope that helps
It appears from your description that you want to compare using one digit before the decimal point and 3 digits after the decimal point, using truncation instead of rounding. So just do that:
>>> def extract(s):
... i = s.find('.')
... return s[i-1:i+4]
...
>>> map(extract, ['21:53:28.339', '121082008.3399'])
['8.339', '8.339']
>>>
Use decimal.Decimal instead of float.

Categories