2

As a preface, I must admit that this is my first real attempt to code a simple program from scratch, and I've just begun my foray into learning python.

As a simple project, I wanted to write a program to find the average value of the digits of π. In other words, we all know that π=3.141529....., but I set out to determine the value of (3+1+4+1+5+....)/(# of digits summed).

This was the result:

#retrieve the value of pi
n=math.pi

#request the number of digits of pi to average over
mag=input("how many terms?")
mag=int(mag)-1


#generate a string populated with the whole number values of the digits of py
k=int(round(n*10**(mag),0))
digits=[int(d) for d in str(k)]
print(k)

#sum the specified values of the digits of pi
print(sum(digits))

#recall the length of the string
print(len(digits))

#calculate average
print((sum(digits)/len(digits)))

The code runs well enough, but I am curious about what tweaks I could make to improve the program or simplify it.

Most specifically, I would like to know if there there is a simpler or more direct way to cast the individual digits of pi into a list or string of integers for manipulation. For instance, is there a specific operator one could use to call individual digits of a given number, like digit(0) returns 3 with respect to pi.

Any advice is greatly appreciated!

  • 4
    You may want to get to know http://codereview.stackexchange.com. – deceze May 11 '21 at 07:07
  • Something that immediately sticks out to me is that it assumes the user will type in an integer... – nick012000 May 11 '21 at 07:07
  • I see no big room for improvement here. The only thing I could comment on is your `int(mag)` which might produce an error if the user input cannot be cast to integer. You might want to put it in a `try-except` block within a `while` statement. Have a look at this [post](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Ma0 May 11 '21 at 07:09
  • 1
    Hmm... you are aware that your program is likely to give erroneous values if the number or asked digits is greater than 15, aren't you? `math.pi` is a ([IEEE 764](https://fr.wikipedia.org/wiki/IEEE_754)) 64 bits floating point **approximation** of the real pi value. The mantissa only contains 48 bits and floating point number cannot be accurate past 15 or 16 decimal digits. – Serge Ballesta May 11 '21 at 07:13
  • Yes Serge, I did notice that the results would start to diverge from my "pen and paper" results as the magnitude of the input grew, some of which I attributed to rounding errors, though I was not aware of the issue you address. I appreciate the insight! – david MITCHELL May 11 '21 at 07:34

0 Answers0