Python 2 decimals Points [duplicate] - python

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)

Related

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

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

Force python to print a certain number of decimal places [duplicate]

This question already has answers here:
Python Decimals format
(6 answers)
Closed 3 years ago.
I have a python program which takes some floating type values and writes to a file.
I round these numbers to 6 decimal places and then convert to a string type before writing to file.
file.write(str(round(value,6)))
However with certain numbers the value written to file is in the format shown below.
e.g. 3e-06 or 4e-03
How can I avoid this and instead write out in decimal format like
0.000003 and 0.004000
How can I print exactly 6 figures after the decimal point.
You can use the f-string f'{value:.6f}'.
Example:
value = 0.234
print(f'{value:.6f}')
value = 1
print(f'{value:.6f}')
value = 0.95269175
print(f'{value:.6f}')
Output:
0.234000
1.000000
0.952692
Also, in the answer linked in a comment, there was reference to :g. That can work, but probably not in this situation, because g may print scientific notation where appropriate, and discards insignificant zeroes. Consider a slightly modified example using g:
value = 0.234
print(f'{value:.6g}')
value = 1
print(f'{value:.6g}')
value = 0.000000000095269175
print(f'{value:.6g}')
Output:
0.234
1
9.52692e-11
You can also use basic string formatting:
a = 3e-06
# Outputs 0.000003
print('%.6f' % a)
# Outputs 0.000003000000
print('%.12f' % a)

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.

Index number of decimals in float - python [duplicate]

This question already has answers here:
Print pi to a number of decimal places
(8 answers)
Closed 4 years ago.
I'm writing a program that estimates the value of pi. I want to implement that you in the command line can specify when the result have the specified number of correct decimals.
Example:
python est_pi.py 3
should end the script when the estimation is 3.141...
Is it possible to have a variable real_pi = 3.14159... and then index into the number of decimals or is there any other solution to this problem?
If You can round your result using:
round(0.333333, N)
Where N is the parameter in input of your script
all the details are there: Round float to x decimals?
When you reached the needed precision, you can format the display through:
format(66.66666666666, '.'+str(N)+'f')
That will display your 66.666... with N digits.
In python 3.6 you have the f-string:
value = 2.34558
precision = N
width = 4
print(f'result: {value:{width}.{precision}f}')
Everything is detailed there: Limiting floats to two decimal points

How to tell python I need the decimals? [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 8 years ago.
My program is to find the number of types, the number of tokens, and the type-to-token ratio. However, I don't know how to tell Python the answer to ttr is not an integer.
from nltk.corpus import inaugural
print inaugural.fileids()
tokens = inaugural.words("1789-Washington.txt")
numtokens = len(tokens)
print numtokens
types = sorted(set(tokens))
numtypes = len(types)
print numtypes
# This is the part I'm unsure about.
ttr = numtypes/numtokens
print ttr
If you are working in Python 3, the division operator / is performing floating point division by default:
>>> 3 / 2
1.5
>>> 4 / 2
2.0
since integer division is handled by the // operator.
In Python 2.x, if you want decimal accuracy in integer division, you can convert either the nominator or the denominator to float(), like this:
ttf = float(numtypes) / numtokens
Alternatively, as tobias_k points out, you can do
>>> from __future__ import division
>>> 3 / 2
1.5
to get Python3-esque division in Python 2.x

Categories

Resources