简体   繁体   English

提取鼠尾草中数字的第n位数字

[英]Extract the n-th digit of a number in Sagemath

How is it possible to extract the n-th digit of a number in Sagemath? 如何在Sagemath中提取数字的第n位数字? We have to compute the 13787th digit from pi + e in Sagemath. 我们必须根据Sagemath中的pi + e计算出第13787位数字。 My approach was the following: 我的方法如下:

sage: xi = e + pi
....: var1 = xi.n(digits=13786+1)
....: var2 = xi.n(digits=13787+1)
....: var3 = ((var2-var1) * 10^13787).trunc()
....: var3
0

Which gave me 0 back, however it should be 9 . 这给了我0 ,但是应该是9

The digit is indeed 9. But the subsequent digits are also 9: this part of decimal expansion goes ...9999237... Rounding rolls these 9s to 0s, carrying 1 to a higher digit. 该数字确实是9。但是随后的数字也是9:十进制扩展的该部分变为... 9999237 ...舍入将这9s滚动为0,将1携带到更高的数字。

So you need some extra digits in order to avoid the digit you are interested in from being affected by rounding. 因此,您需要一些额外的数字,以避免您感兴趣的数字受舍入影响。 How many depends on the number; 多少取决于数量; we don't know in advance if there isn't a sequence of one billion of 9s starting from that position. 我们事先不知道从该位置开始是否有10亿个9的序列。 Here I use 10 extra digits 在这里我使用10个额外的数字

xi = e + pi
n = 13787
offset = 1 + floor(log(xi, 10))   # the first significant figure is not always the first digit after decimal dot, so we account for that 
extra = 10
digit = int(str(xi.n(digits = n + offset + extra))[-1 - extra])

This returns 9. I think extracting with str is more reliable than subtracting two nearly-equal numbers and hoping there won't be additional loss of precition there. 返回9。我认为用str提取比减去两个几乎相等的数更可靠,希望在那里不会造成额外的损失。

Of course, including a magic number like 10 isn't reliable. 当然,包含10这样的魔术数字是不可靠的。 Here is a better version, which starts with 10 extra digits but then increases the number until we no longer have 00000000... as a result. 这是一个更好的版本,它以10个额外的数字开头,然后增加数量,直到不再有000000000 ...为止。

xi = e + pi
n = 13787
offset = 1 + floor(log(xi, 10))
extra = 10
while True:
   digits = str(xi.n(digits = n + offset + extra))[-1 - extra:]
   if digits == "0" * len(digits):
       extra *= 2
   else:
       digit = int(digits[0])
       break
print(digit)

This will loop forever if the digits keep coming as 0, and rightly so : without actually knowing what the number is we can never be sure if the ...0000000... we get is not really ...999999999942... rounded up. 如果数字保持为0,这将永远循环, 这是正确的 :在不知道实际数字是多少的情况下,我们永远无法确定... 0000000 ...得到的不是真的... 999999999942 ...舍入了起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM