import math
def GeoSum(k):
if (k == 0):
return 1
return GeoSum(k - 1) + 1 / math.pow(2,k)
k = int(input())
ans = (GeoSum(k))
print(ans)
Example: at n=4
output is 1.9375
but how to get the output as 1.93750
import math
def GeoSum(k):
if (k == 0):
return 1
return GeoSum(k - 1) + 1 / math.pow(2,k)
k = int(input())
ans = (GeoSum(k))
print(ans)
Example: at n=4
output is 1.9375
but how to get the output as 1.93750
You can use the Decimal module which is very useful for increasing the precision of a floating-point number.
import math
import decimal
from decimal import *
getcontext().prec = 5 #Since you want the 5 level of precision
def GeoSum(k):
if (k == 0):
return 1
return GeoSum(k - 1) + 1 / Decimal(math.pow(2,k))
k = int(input())
ans = (GeoSum(k))
#If you want to print the trailing zeros as well. Then do as following
print('{:.5f}'.format(ans))
Note: Kindly note that for the input 4
you have the maximum precision of 1.9375
. If you give some other inputs you will see the increase in precision.
If you want the trailing zeros in the output to be kept check this link trailing zeros.
Hope this helps you.