0

I am plotting the digits of pi on a matplotlib graph, however in order to do this I must split the digits into individual integers. I am using math.pi for this, is there any other way I could do it to make it easier?

I think .split() only works on strings however I may be wrong.

Einstein.py
  • 61
  • 1
  • 9

3 Answers3

1

You are correct that strings have a .split() method and doubles do not.

I think you are thinking about the number as a string, though. Numbers don't really have separate digits, except in their textual representation in some base. So, you could convert the number to a string and go from there.

Eg.

text = "%.20f" % math.pi
digits = [int(s) for s in text if s != "."]
print(digits)
dsh
  • 12,037
  • 3
  • 33
  • 51
1

Do you want to split each digit into a list? If so, I would convert it to a string (since numbers are treated as the number itself and not digits that make it up) Then remove the decimal point by making a list that excludes decimal points.

import math

listOfDigits = [item for item in str(math.pi) if item != "."]
Max
  • 1,325
  • 9
  • 20
0

You can do this with a generator:

def split_number(number):
    number_as_string = str(number)
    for character in number_as_string:
        if not character.isdigit():
            continue
        yield int(character)

import math
print(list(split_number(math.pi)))
# [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9]

Or if you prefer a one-liner:

list(int(character) for character in str(math.pi) if character.isdigit())
# or
[int(character) for character in str(math.pi) if character.isdigit()]

I believe these answers are preferable because of the use of isdigit instead of special-casing only the . character.

Scott Colby
  • 1,370
  • 12
  • 25