Nakul Parmar
Nakul Parmar

Reputation: 7

Format decimal places in print() method?

I am trying to write a program for finding the sum upto nth term of the Leibniz Series.

I want to print answers on different lines correct upto 15 decimal places.

The code.

a=[]
for _ in range(int(input().strip())):
   n=int(input().strip())
   a.append(sum([(-1)**i/(2*i+1) for i in range(n)]))
print("\n".join(str(i) for i in a))

My output:

0.7604599047323508
0.77290595166696

Expected Output:

0.760459904732351
0.772905951666960

NOTE- I want to keep the code as minimal as possible

Upvotes: 1

Views: 200

Answers (3)

void
void

Reputation: 2642

If you want,

0.7604599047323508

to be rounded-off upto 15 decimal places like this,

0.760459904732351

That's pretty simple:

i = 0.7604599047323508
print(i)
print("%.15f" % i) 

Output:

0.7604599047323508
0.760459904732351

If you have number of decimal length less than 15. Then 0s are added. Take a look,

x = 0.760459904732 #Less than 15

print(x)
print("%.15f" % x)

Output:

0.760459904732
0.760459904732000

UPDATE:

There is also the built-in function round() you can use that too. round(value,places)

Example:

>>> a=0.7604599047323508
>>> round(a,15)
0.760459904732351

For your code: Using print()

a=[]
for __ in range(int(input().strip())):
   n=int(input().strip())
   a.append(sum([(-1)**i/(2*i+1) for i in range(n)]))

for i in a:
    print("%.15f" % i)

Also why do you use _ ? Use some other name instead. To know the purpose of _ try this in your interpreter.

>>> a=10
>>> b=20
>>> a+b
30
>>> _
30
>>> a*10000
100000 variable name.
>>> _
100000
>>> a
10

_ stores the most recent calculation in interpreter. _ is used as a throwaway variable __ is better than _ I guess.

Upvotes: 2

Akshat
Akshat

Reputation: 185

You can use the Decimal module to get exact precision

from decimal import *
for x in range (0,int(input())):
    s,n=Decimal('0'),int(input())
    for i in range(0,n):
        s+= Decimal(str(((-1)**i)/((2*i)+1)))
    print (s)

Upvotes: 0

gionni
gionni

Reputation: 1303

Here you go:

"\n".join("{:.15f}".format(i) for i in a)

Upvotes: -1

Related Questions