如何在python十进制模块中得到精确的最后一位数

dvtswwa3  于 2023-02-07  发布在  Python
关注(0)|答案(2)|浏览(144)

我正在尝试创建一个程序,通过使用decimal模块来查找2的平方根的第n位数字
√2 = 1.414213(5)6237309504880168872420969807856967187537694......
如果用户请求第8位数字,则程序生成8位数字√2(1.4142135)并打印最后一位数字(5)

nth_digit_of_sqrt_of_2 = 8  # i wanna find the 8th digit of √2

expected_sqrt_of_2 = "14142135"  # 5 first digits of √2 (no decimal point)
expected_answer =  5 # the last digit

但实际上发生了什么

from decimal import Decimal, getcontext

getcontext().prec = nth_digit_of_sqrt_of_2 # set precision to 5 digits

decimal_sqrt_of_2 = Decimal('2').sqrt()
decimal_sqrt_of_2 = str(decimal_sqrt_of_2).replace('.', '')  # convert to string and remove decimal point
print(decimal_sqrt_of_2)
# actual_sqrt_of_2 = 14142136
# actual_answer = 6

我尝试使用ROUND_DOWN和ROND_FLOOR,但似乎也不起作用

f87krz0w

f87krz0w1#

你可以试试这个:

from decimal import Decimal, getcontext

nth_digit_of_sqrt_of_2 = 8
getcontext().prec = nth_digit_of_sqrt_of_2 + 1 # set precision to n+1 digits

decimal_sqrt_of_2 = Decimal('2').sqrt()
decimal_sqrt_of_2 = str(decimal_sqrt_of_2).replace('.', '')  # convert to string and remove decimal point
print(int(str(decimal_sqrt_of_2)[nth_digit_of_sqrt_of_2 - 1]))
jv2fixgn

jv2fixgn2#

您可以使用以下命令获取数字:

def digit(n):
    from decimal import Decimal
    return str(Decimal('2').sqrt()).replace('.', '')[n-1]
    
digit(8)
#'5'
digit(7)
#'3'
digit(9)
#'6'

**编辑:**如果您想要更多位数,您可以自定义自己的功能。

def sqrut(x, digits):
    x = x * (10**(2*digits))
    prev = 0
    next = 1 * (10**digits)
    while prev != next:
        prev = next
        next = (prev + (x // prev)) >> 1
    return str(next)

假设你需要1000位2的平方根数字,你可以得到

print(sqrut(2, 1000))

'14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372352885092648612494977154218334204285686060146824720771435854874155657069677653720226485447015858801620758474922657226002085584466521458398893944370926591800311388246468157082630100594858704003186480342194897278290641045072636881313739855256117322040245091227700226941127573627280495738108967504018369868368450725799364729060762996941380475654823728997180326802474420629269124859052181004459842150591120249441341728531478105803603371077309182869314710171111683916581726889419758716582152128229518488472'

现在,如果您想要第8位数字,则:

print(sqrut(2, 1000)[8-1])
#'5'

#9th digit then:
print(sqrut(2, 1000)[9-1])
#'6'

#nth digit then:
print(sqrut(2, 1000)[n-1])

相关问题