How to round number to one decimal places python? [duplicate] - python

This question already has answers here:
python incorrect rounding with floating point numbers
(4 answers)
Closed 4 months ago.
I'm trying to round my numbers to 1 decimal places. This could be with any number with many decimal places or no decimal places.
But now I'm trying to go with 8.25 as an example because when I try rounding it it always be cut or rounded to 8.2 but I'm looking for it to be 8.3 . Pls help
print(round(result,1)) #result -> 8.2
"{:.1f}".format(result) #result -> 8.2 I was thinking about adding 0.05 to it and cut for 1 decimal place but I feel like it might affect the other number since it could be any number

import math
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier
print(round_up(8.25, 1))
output: 8.3

You can still use round().
result = 8.2546535
print(round(result,2))
Output
8.25
If you always want to round up you can use math.ceil()
import math
math.ceil(8.211234 * 10) / 10
Result
8.3

Related

Why don't large floats in Python 3 get cast to integers properly? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Is floating point arbitrary precision available?
(5 answers)
Closed 7 years ago.
I don't know if this is an obvious bug, but while running a Python script for varying the parameters of a simulation, I realized the results with delta = 0.29 and delta = 0.58 were missing. On investigation, I noticed that the following Python code:
for i_delta in range(0, 101, 1):
delta = float(i_delta) / 100
(...)
filename = 'foo' + str(int(delta * 100)) + '.dat'
generated identical files for delta = 0.28 and 0.29, same with .57 and .58, the reason being that python returns float(29)/100 as 0.28999999999999998. But that isn't a systematic error, not in the sense it happens to every integer. So I created the following Python script:
import sys
n = int(sys.argv[1])
for i in range(0, n + 1):
a = int(100 * (float(i) / 100))
if i != a: print i, a
And I can't see any pattern in the numbers for which this rounding error happens. Why does this happen with those particular numbers?
Any number that can't be built from exact powers of two can't be represented exactly as a floating point number; it needs to be approximated. Sometimes the closest approximation will be less than the actual number.
Read What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Its very well known due to the nature of floating point numbers.
If you want to do decimal arithmetic not floating point arithmatic there are libraries to do this.
E.g.,
>>> from decimal import Decimal
>>> Decimal(29)/Decimal(100)
Decimal('0.29')
>>> Decimal('0.29')*100
Decimal('29')
>>> int(Decimal('29'))
29
In general decimal is probably going overboard and still will have rounding errors in rare cases when the number does not have a finite decimal representation (for example any fraction where the denominator is not 1 or divisible by 2 or 5 - the factors of the decimal base (10)). For example:
>>> s = Decimal(7)
>>> Decimal(1)/s/s/s/s/s/s/s*s*s*s*s*s*s*s
Decimal('0.9999999999999999999999999996')
>>> int(Decimal('0.9999999999999999999999999996'))
0
So its best to always just round before casting floating points to ints, unless you want a floor function.
>>> int(1.9999)
1
>>> int(round(1.999))
2
Another alternative is to use the Fraction class from the fractions library which doesn't approximate. (It justs keeps adding/subtracting and multiplying the integer numerators and denominators as necessary).

How to round to two decimal places in python? [duplicate]

This question already has answers here:
How to round to 2 decimals with Python? [duplicate]
(21 answers)
Closed last year.
Im trying to calculate a bill in python for hw. Cant figure out how to round the numbers to two decimal places. Here's what I have so far. Every time I try the round function, it doesnt work and gives me an error message. Help?!
ss_cost = 3.95 * 2
hb_cost = 8.95 * 2
ds_cost = 2.50 * 2
subtotal = (ss_cost) + (hb_cost) + (ds_cost)
tax = (round(subtotal * 0.0475), %.2)
print (tax)`
You missplaced the %.2:
tax = (round(subtotal * 0.0475, 2))
And you don't need the %.
round(number[, ndigits])
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise, the return value has the same type as number.
When it comes to amounts, you shouldn't use round, it's better to use decimal.
from decimal import Decimal
ss_cost = 3.95 * 2
hb_cost = 8.95 * 2
ds_cost = 2.50 * 2
subtotal = (ss_cost) + (hb_cost) + (ds_cost)
tax = Decimal(subtotal * 0.0475).quantize(Decimal("0.00"))
print (tax)
# 1.46

Decimal Precision in Python [duplicate]

This question already has answers here:
Precision of decimals in Python
(1 answer)
Float sum broken? [duplicate]
(2 answers)
Limiting floats to two decimal points
(35 answers)
Closed 4 years ago.
When I run the code
b = 7**7
I get b as 823543
But when I run
b= 823543.0**(1.0/7.0)
It gives me b as 6.999999999999999
If it is something as simple as 4**(1/2) it returns 2.
My question is why doesn't python just return a perfect 7?
Also I was doing this to check if a number can be written n can be written in the form p^q where p>0 and q>1 to do so I did this:
def isPower(self, A):
possible = 0 # Integer value to check if it is possible , 0 assuming it is false initally
if(A==1):
return 1
for i in xrange(2,A-1):
res = float(A)**(1.0/float(i)) #Check if it has sqaure root or cube root up untill A-1
if(res.is_integer()): #If taking the power gives me whole number then saying it is possible
possible = 1
break
return possible
This logic fails with higher numbers like 823543 because the power returns a imprecise value how would I solve this?
You're not using Decimals - you're using floats. They trade off accuracy for speed.
Try this;
from decimal import Decimal
b = 7 ** 7 # 823543
a = Decimal(1) / Decimal(7)
b ** a # returns (for me) Decimal('7.000000000000000000000000004')
Why not rounding:
>>> b= 823543**(1/7)
>>> round(b)
7
>>>
Now you've got 7 (seven)
You should read What Every Computer Scientist Should Know About Floating-Point Arithmetic.
In short: floating point numbers are represented as mantissa and exponent. Something like
0.1234 * 10^1
Where 1234 is the mantissa (the exponent is represented in 2-complement, if I recall correctly)
This means some integer numbers cannot be represented accurately as floats.
You can represent 7 and 823543 exactly as floats, but I don't think that works for 1/7 (don't have a piece of paper at hand): https://www.h-schmidt.net/FloatConverter/IEEE754.html
Also, take into consideration how the n-the root is calculated.

Python 2 decimals Points [duplicate]

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 6 years ago.
I have a quick question in terms of decimals points in Python 2.
Here is the code in Python 2:
a = 1500/1589
print (round(a,2))
#0.0
I thought it would print out a = 0.94 as it did in Python 3. I am just wondering how I could get 2 decimals for my answer.
You need to specify that at least one of the inputs to the division is a floating point number by adding an explicit decimal point.
a = 1500. / 1589
print round(a, 2)
# 0.94
If you do not do this, both 1500 and 1589 are treated as integers and the result of 1500/1589 is required to be an integer (0) as well
1500 / 1589
# 0
print round(1500 / 1589, 2)
# 0.0
As a side note, if you want to print a number with two decimal places, a far easier method is to create a formatted string:
print '%0.2f' % (1500. / 1589)
# 0.94
print '{:.2}'.format(1500. / 1589)
# 0.94
That's because you're making an integer division. For instance do:
a = 1500.0/1589.0
print round(a,2)
Or if you have integers as input:
a = float(1500)/float(1589)
print round(a,2)

Python small decimals automatically round to 0 [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 6 years ago.
I have a simple problem:
print 1 / 100
returns
0
and
print float(1 / 100)
returns
0.0
Why does this happen? Shouldn't it return 0.01? Thank you for any help.
Simple solution!
print 1 / float(100)
Your problem is that by default in Python 2 the division operator will do integer division (rounding down to integer). By making one of the operands a float, Python will divide in the expected way. You were almost there with float(1 / 100), however all this accomplishes is doing the integer division of 1 by 100, which equals zero, then converting zero to a floating point number.
This is a recognized issue in Python 2, fixed in Python 3. If you get tired of writing x / float(y) all the time, you can do from __future__ import division to make the division operator behave as in Python 3.
You are doing integer division. What you've written is, for all intents and purposes:
float(int(1)/int(10))
For example:
assert float(10/3) == 3.0 # True
You need to have at least one of them implicitly or explicitly a float. All of these are valid:
float(1.0/100.0)
float(1.0/100)
float(1/100.0)
float(float(1)/float(100))
etc...
You are doing integer division, when expecting a decimal (float), you can assert an integer to be a float by placing a decimal at the end, i.e.
print 1 / 100.

Categories

Resources