Most Pythonic Way To Round a Float After Calculation - python

Ultimately, I am trying to accomplish the calculation of a number that gives me back 3 decimal places, and round it to 2 decimal places. What I have, is thus:
total = 175
tax = .0875
total += total * tax # giving me my desired total
print total
>>> 190.3125
rounded = round(total, 2) # giving me my desired decimal place
print rounded
>>> 190.31
I was thinking of doing the total and rounded line in one, but it looks jumbled...
Here is what I feel is the fastest way, but does not look as readable as I would like:
total = round((total + (total*tax)), 2)
print total
>>> 190.31
EDIT
Thank you guys for the input in the comments. It seems time is clearly not something to stress here & I am going to run with rounded = round(total, 2) for my code. Thanks again!

I think you should first think pythonically. What is the critical purpose of rounding a float? Do you need to use this rounded float to calculate later or you want to display it? Or you want to store it into a file or database with a consistent format? Different purposes lead to different methods.
If you want to use this rounded float to calculate later, you just don't need to round it. We should not do any additional process before the final calculation as it will only reduce the precision of results without any benefit.
If you want to display this rounded float, you can keep the precision inside variable and use string format: print "%.2f" % total. This will also print out what you want but won't make you lose precision.
If you want to store it into a file or a database, you can just go to rounded = round(total, 2), it is really pythonic and useful.

Related

python: percent format returning zeroes after the decimal place

I am trying to get some percentages to print to 4 decimal places. My code looks like this
for i in range(len(candidates)): #looping through the results
percentage_votes = "{:.4%}".format(results[i][1] / voters) #setting the number to a %
print(f'{results[i][0]}: {percentage_votes} ({results[i][1]})') #print result
When it prints; however, rather than giving me the decimal places of the division, it instead returns all zeros in the 4 decimal places.
Khan: 63.0000% (2218231)
Correy: 20.0000% (704200)
Li: 14.0000% (492940)
O'Tooley: 3.0000% (105630)
What do I need to correct in my code to give me the further divided number? Thanks!
I tried this
"{:.4%}".format(3.4445453543)
Output: '344.4545%'
Which got me thinking that might be the division is not reporting float,
can you try this:
"{:.4%}".format(results[i][1] / float(voters))

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.

I need to create a BMI calculator however it does not round to two decimal places. I was wondering how to do so. This is my code so far in python

height = float(input("What is your height in meters?"))
weight = float(input("What is your weight in kg?"))
sum = weight/height/height
print('The sum is {0} divided by {1} divided by {1} equals {2}'.format(weight,height,sum))
Life will be easier for you, as a programmer, if you use google. And I mean no offence. In this case, just query for python round.
In this particular case, if you want to round a float called BMD to two decimal places then you would use the following expression,
round(BMD,2)
You might also be interested in how to use formatting to achieve a similar result. First I deliberately set BMD to a value that has only two decimal places. I can print it as-is but I have no control. In the second case, I set BMD to a value for quite a few decimal places but this time I limit the number of output decimal places.
In my opinion, it's safer to use round and then use the first formatting option because the second option could stumble with a value such as 345.22 (which occupies more than four columns overall).
>>> BMD = 5.21
>>> print ('BMD is {}'.format(BMD))
BMD is 5.21
>>> BMD = 5.213333333333333
>>> print ('BMD is {:4.2f}'.format(BMD))
BMD is 5.21

Python, How to round up to maximum precision

It's quite a simple question actually, let's say i have this number 1.499998499999999e-98, now if i wanted to round it up to ~1.5e-98 how would i go about it? I tried the round() but it gives me 0.0 which is kind of useless for what i'm working on.
One (kinda 'hacky') way would be to format the number as a string and convert back to float:
>>> x = 1.499998499999999e-98
>>> "%.2e" % x
'1.50e-98'
>>> float("%.2e" % x)
1.5e-98
Other than using round, this will round to significant digits, not "absolute" number of digits.
You can specify the number of digits that you want to round to (see the documentation), and also read the note about rounding being surprising.
Numpy may give you a little more control over rounding.

Doing arithmetic with up to two decimal places in Python?

I have two floats in Python that I'd like to subtract, i.e.
v1 = float(value1)
v2 = float(value2)
diff = v1 - v2
I want "diff" to be computed up to two decimal places, that is compute it using %.2f of v1 and %.2f of v2. How can I do this? I know how to print v1 and v2 up to two decimals, but not how to do arithmetic like that.
The particular issue I am trying to avoid is this. Suppose that:
v1 = 0.982769777778
v2 = 0.985980444444
diff = v1 - v2
and then I print to file the following:
myfile.write("%.2f\t%.2f\t%.2f\n" %(v1, v2, diff))
then I will get the output: 0.98 0.99 0.00, suggesting that there's no difference between v1 and v2, even though the printed result suggests there's a 0.01 difference. How can I get around this?
thanks.
You said in a comment that you don't want to use decimal, but it sounds like that's what you really should use here. Note that it isn't an "extra library", in that it is provided by default with Python since v2.4, you just need to import decimal. When you want to display the values you can use Decimal.quantize to round the numbers to 2 decimal places for display purposes, and then take the difference of the resulting decimals.
>>> v1 = 0.982769777778
>>> v2 = 0.985980444444
>>> from decimal import Decimal
>>> d1 = Decimal(str(v1)).quantize(Decimal('0.01'))
>>> d2 = Decimal(str(v2)).quantize(Decimal('0.01'))
>>> diff = d2 - d1
>>> print d1, d2, diff
0.98 0.99 0.01
I find round is a good alternative.
a = 2.000006
b = 7.45001
c = b - a
print(c) #This gives 5.450004
print(round(c, 2)) ##This gives 5.45
I've used poor man's fixed point in the past. Essentially, use ints, multiply all of your numbers by 100 and then divide them by 100 before you print.
There was a good post on similar issues on Slashdot recently.
The thing about the float type is that you can't really control what precision calculations are done with. The float type is letting the hardware do the calculations, and that typically does them the way it's most efficient. Because floats are (like most machine-optimized things) binary, and not decimal, it's not straightforward (or efficient) to force these calculations to be of a particular precision in decimal. For a fairly on-point explanation, see the last chapter of the Python tutorial. The best you can do with floats is round the result of calculations (preferably just when formatting them.)
For controlling the actual calculations and precision (in decimal notation, no less), you should consider using Decimals from the decimal module instead. It gives you much more control over pretty much everything, although it does so at a speed cost.
What do you mean "two significant figures"? Python float has about 15 sigfigs, but it does have representation errors and roundoff errors (as does decimal.Decimal.) http://docs.python.org/tutorial/floatingpoint.html might prove an interesting read for you, along with the great amount of resources out there about floating point numbers.
float usually has the right kind of precision for representing real numbers, such as physical measurements: weights, distances, durations, temperatures, etc. If you want to print out a certain way of displaying floats, use the string formatting as you suggest.
If you want to represent fixed-precision things exactly, you probably want to use ints. You'll have to keep track of the decimal place yourself, but this is often not too tough.
decimal.Decimal is recommended way too much. It can be tuned to specific, higher-than-float precision, but this is very seldom needed; I don't think I've ever seen a problem where this was the reason someone should use decimal.Decimal. decimal.Decimal lets you represent decimal numbers exactly and control how rounding works, which makes it suitable for representing money in some contexts.
You could format it using a different format string. Try '%.2g' or '%.2e'. Any decent C/C++ reference will describe the different specifiers. %.2e formats the value to three significant digits in exponential notation - the 2 means two digits following the decimal point and one digit preceding it. %.2g will result in either %.2f or %.2e depending on which will yield two significant digits in the minimal amount of space.
>>> v1 = 0.982769777778
>>> v2 = 0.985980444444
>>> print '%.2f' %v1
0.98
>>> print '%.2g' %v1
0.98
>>> print '%.2e' %v1
9.83e-01
>>> print '%.2g' %(v2-v1)
0.0032
>>> print '%.2e' %(v2-v1)
3.21e-03

Categories