[Tutor] Count for loops

boB Stepp robertvstepp at gmail.com
Tue Apr 11 23:40:46 EDT 2017


On Tue, Apr 11, 2017 at 2:18 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Tue, Apr 11, 2017 at 9:48 AM, Rafael Knuth <rafael.knuth at gmail.com>
> wrote:
>
>> I tested this approach, and I noticed one weird thing:
>>
>> Pi_Number = str(3.14159265358979323846264338327950288419716939)
>> Pi_Number = "3" + Pi_Number[2:]

Minor note:  If the OP's original effort was to reproduce his pi
approximation with a decimal point, then his slice indexing should
have been Pi_Number[1:]

>> print(Pi_Number)
>>
>> == RESTART: C:\Users\Rafael\Documents\01 - BIZ\CODING\Python
>> Code\PPC_56.py ==
>> 3141592653589793
>> >>>
>>
>> How come that not the entire string is being printed, but only the
>> first 16 digits?
>>
>
> That's due to how str() works; it's simply making (its own conception) of a
> pretty representation of what's fed to it, which in the case of
> floating-point numbers means that they're represented to 16 digits
> precision.
> str(3.14159265358979323846264338327950288419716939) is _not_ the same as
>     "3.14159265358979323846264338327950288419716939"
>
> From the docs: "Return a string containing a nicely printable
> representation of an object. For strings, this returns the string itself.
> The difference with repr(object) is that str(object) does not always
> attempt to return a string that is acceptable to eval()
> <https://docs.python.org/2/library/functions.html#eval>; its goal is to
> return a printable string."

I have to say I am surprised by this as well as the OP.  I knew that
str() in general makes a nice printable representation, but I did not
realize that using str() on an arbitrarily typed in "float-like" value
would convert the typed in value to a normal float's max precision.
So I guess the only way to get a string representation of such a
number is to do something like:

py3: str_pi = '3.14159265358979323846264338327950288419716939'
py3: len(str_pi)
46
py3: str_pi
'3.14159265358979323846264338327950288419716939'

or perhaps:

py3: new_pi = '3' + '.' + '14159265358979323846264338327950288419716939'
py3: len(new_pi)
46
py3: new_pi
'3.14159265358979323846264338327950288419716939'

or even with str():

py3: new_pi = '3' + '.' + str(14159265358979323846264338327950288419716939)
py3: len(new_pi)
46
py3: new_pi
'3.14159265358979323846264338327950288419716939'

since in Python 3 integers are unlimited in precision (within RAM constraints).

I guess this has to be this way or the conversions of actual Python
numerical literals to strings and back again would otherwise be
inconsistent.

Still learning!

-- 
boB


More information about the Tutor mailing list