0
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

Praveen Lohar
  • 17
  • 1
  • 6

1 Answers1

0

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.

Saurav Rai
  • 2,171
  • 1
  • 15
  • 29
  • This does not output a trailing zero. Also, please be aware that comments in Python start with ``#``, not ``//``. ``//`` is the floor division operator. – MisterMiyagi Jun 20 '20 at 06:06
  • @MisterMiyagi Thanks for the suggestion. I have added that part as well. I have added some more details to him. Anyways thanks for pointing out that part and kindly unvote the answer if you have given the downvote for that reason since the answer is useful for him now. Thank you once again. – Saurav Rai Jun 20 '20 at 06:10
  • The new, relevant part is [a link-only answer](https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers). Please include the relevant information *in you answer*. – MisterMiyagi Jun 20 '20 at 06:21
  • @MisterMiyagi Kindly check it now. Thanks. – Saurav Rai Jun 20 '20 at 06:30
  • Thanks it helped me a lot..i learned something new @Saurav Rai – Praveen Lohar Jun 20 '20 at 12:25
  • Thank u @Saurav Rai for helping me out. – Praveen Lohar Jun 20 '20 at 12:33
  • @PraveenLohar I am glad that it helped you. Kindly accept the answer as well for the benefit of future users also. Thanks. – Saurav Rai Jun 20 '20 at 12:49