给定小数位数的平方根的近似值

问题描述 投票:1回答:2

我需要编写一个读取2个输入的程序:1st包含一个不大于10亿的非负整数n(109),第二个包含一个非负整数k(期望的精度,以小数位表示),不大于1万(104)。该程序应在标准输出中打印出一个数字。该数字应为n的平方根,精度为k个小数位数,在需要四舍五入时总是四舍五入。(如果k = 0,则结​​果应四舍五入为最接近的整数)。

这是我的第二项任务,我编写了以下代码,使用牛顿法对其进行计算。

程序可以自由地假定输入将满足上述条件

程序有效,但小数位数始终不正确,为解决此问题,我尝试添加一些条件以根据读取的第一个数字增加一个单位的getcontext()。prec。但由于以下原因未能解决问题:-x <10 ^ 2:结果正确-x> = 10 ^ 2&x <10 ^ 4:Resul正确的单位为x = 3000,则小数位不正确为-1。

from decimal import *
from _decimal import Decimal



def sqrt(x):

    last_guess = x/2.0
    error = (1/(10**y))

    while True:
        guess = Decimal((last_guess + x/last_guess )/2)
        if abs(Decimal(guess) - Decimal(last_guess)) < error:  # example threshold
            return Decimal(guess)
        last_guess = Decimal(guess)
        print(last_guess)


x = int(input("Calculate the square root  of : "))

y = int(input("Decimal positions : "))

if x < 10**2:
    getcontext().prec = y + 1

if x >= 10**2 and x < 10**4:
    getcontext().prec = y + 2

if x >= 10**4 and x < 10**6:
    getcontext().prec = y + 3

if x >= 10**6 and x < 10**8:
    getcontext().prec = y + 4

if x >= 10**8 and x < 10**10:
    getcontext().prec = y + 5

if x >= 10**10 and x < 10**12:
    getcontext().prec = y + 6

if x >= 10**12 and x < 10**14:
    getcontext().prec = y + 7

a =sqrt(x)

if x < 10**2:
    getcontext().prec = y + 1

if x >= 10**2 and x < 10**4:
    getcontext().prec = y + 2

if x >= 10**4 and x < 10**6:
    getcontext().prec = y + 3

if x >= 10**6 and x < 10**8:
    getcontext().prec = y + 4

if x >= 10**8 and x < 10**10:
    getcontext().prec = y + 5

if x >= 10**10 and x < 10**12:
    getcontext().prec = y + 6

if x >= 10**12 and x < 10**14:
    getcontext().prec = y + 7


print("The square root of ",x," is : ", Decimal(a))
# print("The original number: ", Decimal(a)**2)

用于输入

87658

您的程序应打印出来

93.62157870

用于输入

30003

您的程序应打印出来

54,772

python decimal square-root newtons-method
2个回答
0
投票

尝试一下。如果您遇到相同的问题,请对此发表评论,我将尝试看看发生了什么。我也有一个问题:您是否希望k为'。'之后的小数位数。或只是总数的地方?我在这里使用的程序将使其在'。'之后的精度。始终是您想要的精度。程序结束后,我将向您展示另一种方法。


0
投票

谢谢您的回答,但是我必须使用牛顿法,我的代码可以运行,但是它始终不能输入正确的小数位,例如:

© www.soinside.com 2019 - 2024. All rights reserved.