This question already has answers here:
Limiting floats to two decimal points
(35 answers)
Closed 8 years ago.
I am working on a python project and get a problem.
I have a for loop that makes a list with numbers. The problem is when I print out the list to check if the numbers are correct.
Some of the more simpler calculations are:
2.6 * 3 and 1.3 * 9
If you check with a calculator you should get 7.8 and 11.7, but I get 7.800000000000001 and 11.700000000000001
Which is not a big problem, but I don't like how it looks. (First world problem, I know)
Is there any way to fix it?
Use string format?
print "%.2f" % (2.6 * 3)
The %.2f means print a float to 2dp
You can use format to display the output you want:
>>> print(format(2.6 * 3, ".1f"))
7.8
Here ".1f" means "floating point number to one decimal place".
You can use format print.
res = 2.6*3
"%0.2f" % res
Here's a complete example with a list.
>>> n = [1.9, 7.8 , 9,3.4]
>>> print n
[1.8999999999999999, 7.7999999999999998, 9, 3.3999999999999999]
>>> twodecimals = ["%.2f" % v for v in n]
>>> print twodecimals
['1.90', '7.80', '9.00', '3.40']
>>> print twodecimals[0]
1.90
%.2f means prints only 2 decimal points. Similarly, .1f means 1 decimal point and so on.
Related
This question already has answers here:
How to print float to n decimal places including trailing 0s?
(5 answers)
Closed 3 years ago.
I want to print my result with a specific number of decimal places inside of a for loop where the value of it is the number of decimal places to be printed.
Below is a sample of the relevant part of the code:
for i in range (-15, -7):
print ('Valor do erro:' , 10**i, 'Valor da serie:', count, '------->', '%.16f' % adder(count))
Format-specifiers can be nested:
>>> for i in range(1, 5):
... print("{:.{}f}".format(1/i, i))
...
1.0
0.50
0.333
0.2500
Here, 1/i goes to the first (outer) {...} and i to the second (inner) {}.
Note that the number of decimal places can not be negative, though. For this, you might just want to use scientific notation instead.
>>> for i in range(-2, 3):
... print("{:.2e}".format(10**i))
...
1.00e-02
1.00e-01
1.00e+00
1.00e+01
1.00e+02
This question already has answers here:
How to truncate float values?
(31 answers)
Closed 4 years ago.
I want convert a number to a float number with 3 decimal point but I want it without rounding.
For example:
a = 12.341661
print("%.3f" % a)
This code return this number:
12.342
but I need to original number,I need this:
12.341
I write a code that receive a number form user and convert it to a float number.
I have no idea that what is the number entered with user.
My first thought was to change print("%.3f" % a) to print("%.3f" % (a-0.0005)) but it does not quite work: while it outputs what you want for a=12.341661, if a=12.341 it outputs 12.340, which is obviously not right.
Instead, I suggest doing the flooring explicitly using int():
a = 12.341661
b = int(a*1000)/1000.
print(b)
This outputs what you want:
12.341
To get 3 decimals out even if the input has fewer, you can format the output:
a = 3.1
b = int(a*1000)/1000.
print("%.3f" % b)
Outputs:
3.100
try str and slicing
a = 12.341661
b = str(int(a))
c = str(a - int(a))[1:5]
d = b + c
print(d)
This question already has answers here:
Python modulo on floats [duplicate]
(3 answers)
Closed 5 years ago.
I'm trying to check in Python if a math.log(x, base) has decimal or not:
import math
# math.log(8, 2) = 3
print math.log(8)
print math.log(2)
print math.log(8) / math.log(2)
print 2.07944154168 % 0.69314718056
print math.log(8) % math.log(2)
Output is:
2.07944154168
0.69314718056
3.0
0.0
0.69314718056
Why does fourth print row return zero but fifth does not?
This will probably be closed for being a duplicate, but just so one can see how this plays out:
>>> import math
>>> math.log(8)
2.0794415416798357
>>> math.log(2)
0.6931471805599453
Now let's say you need to compute math.log(8) % math.log(2). You need to compute the remainder after dividing math.log(2) into math.log(8). Let's see, does it go in 3 times?
0.6931471805599453
+ 0.6931471805599453
+ 0.6931471805599453
--------------------
2.0794415416798359
Woah! We overshot the value of 2.0794415416798357 which means it actually goes in TWO times:
0.6931471805599453
+ 0.6931471805599453
--------------------
1.3862943611198906
Okay so what is the remainder?
2.0794415416798359
- 1.3862943611198906
--------------------
0.6931471805599453
So TL;DR your remainder is close to math.log(2) because of rounding errors. It does not go in exactly three times. It goes in two times with just about math.log(2) left over.
Yes when you print the quotient it says 3.0 but again, this is all rounding error in floating point, which is not unique to Python.
This is what I get using python 3
>>> print (math.log(8))
2.0794415416798357
>>> print (math.log(2))
0.6931471805599453
>>> print (math.log(8) / math.log(2))
3.0
>>> print (2.07944154168 % 0.69314718056)
0.0
>>> print (math.log(8) % math.log(2))
0.6931471805599452
>>> print (2.0794415416798357 % 0.6931471805599453)
0.6931471805599452
It looks like in your example (python 2 ?), the precision of math.log is not enough.
I have Googled, but couldn't find a proper answer to this.
Let's say we have floats and we get their averages. Their averages are like this:
3.5
2.5
5
7
So we've got 4 numbers (who are not in a list anymore). Two numbers with a decimal and two whole numbers.
What I want to do is, to print these numbers and keep them like this. My problem is, though, that when I use %.1f, it makes 5.0 and 7.0 from 5 and 7, while I want to keep them as they are (so keep them as a whole number).
So I'd like to print them exactly as they are, but I don't know how. Float adds decimal points to whole numbers. Converting them to an int, removes the needed decimals.
Both options are not what I want.
Can someone point me in the right direction?
Edit: the relevant code, as asked:
# I have a list of numbers and I am calculating their average and rounding them first.
get_numbers = map(float, line[-1])
average_numbers = sum(get_numbers) / len(get_numbers)
rounded_numbers= round(average_numbers * 2) / 2
# So now, I've got the numbers: 3.5, 2.5, 5, 7
print "The numbers are: %.1f" % (rounded_numbers)
You can use floats' is_integer method. It returns True if a float can be represented as an integer (in other words, if it is of the form X.0):
li = [3.5, 2.5, 5.0, 7.0]
print([int(num) if float(num).is_integer() else num for num in li])
>> [3.5, 2.5, 5, 7]
EDIT
After OP added their code:
Instead of using list comprehension like in my original example above, you should use the same logic with your calculated average:
get_numbers = map(float, line[-1]) # assuming line[-1] is a list of numbers
average_numbers = sum(get_numbers) / len(get_numbers)
average = round(average_numbers * 2) / 2
average = int(average) if float(average).is_integer() else average
print average # this for example will print 3 if the average is 3.0 or
# the actual float representation.
Similar to the previous answer:
[int(i) if int(i) == i else i for i in li]
Or:
[int(i) if not i % 1 else i for i in li]
Technically, if you have floats and get their averages, you SHOULD get floats back. But if you just want to print them, the following should work well:
print('{} {} {} {}'.format(3.5, 2.5, 5, 7))
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Python float - str - float weirdness
I run the following code in python on codepad.org:
num = 1.6
print num
list = [num]
print list
num2 = list[0]
print num2
And I get the following output:
1.6
[1.6000000000000001]
1.6
Why the tiny deviation in the list?
list.__str__ calls repr on its elements, where as print calls str:
>>> str(1.6)
'1.6'
>>> repr(1.6)
'1.6000000000000001'
Since floating point numbers are not guaranteed to be exact (and cannot be exact for values that can't be expressed as a * 2b for integers a,b), both representations are correct, or, in other words:
>>> 1.6 == 1.6000000000000001
True