这个找到根的代码是怎么回事?

2024-10-04 05:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到问题的线路有:

  1. while not withinEpsilon(ans**pwr, val, epsilon):withinEpsilon为false时,是否继续执行?

  2. 为什么我需要一个负的绝对值,为什么它在max val和1之间?你知道吗

    low = -abs(val)    
    high = max(abs(val), 1.0)
    
  3. if isEven(pwr) and val < 0:如果力量是均等的,那又有什么关系呢?

以下是完整代码:

def isEven(i):
    '''assumes i is a positive int
       returns true if i is even, otherwise False'''
    return i%2 == 0

def findRoot(pwr, val, epsilon):
    '''assumes pwr an int; val, epsilon floats > 0'''
    assert type(pwr) == int
    assert type(val) == float
    assert type(epsilon) == float
    assert pwr > 0 and epsilon > 0
    if isEven(pwr) and val < 0:
        return None
    low = -abs(val)
    high = max(abs(val), 1.0)
    ans = (high + low)/2.0
    while not withinEpsilon(ans**pwr, val, epsilon):
        #print 'ans =', ans, 'low =', low, 'high =', high
        if ans**pwr < val:
           low = ans
        else:
           high = ans
        ans = (high + low)/2.0
    return ans

def testFindRoot():
    """x float, epsilon float, pwr positive int"""
    for x in (-1.0, 1.0, 3456.0):
        for pwr in (1, 2, 3):
            ans = findRoot(pwr, x, 0.001)
            if ans == None:
                print 'The answer is imaginary'
            else:
                print ans, 'to the power', pwr,\
                'is close to', x 

testFindRoot()

Tags: ifisvalabsassertfloatmaxint
1条回答
网友
1楼 · 发布于 2024-10-04 05:24:37
  1. 是的,代码指定在withinEpsilon为False时继续循环。你知道吗
  2. 代码使用dichotomy查找“ans”,例如“0<;| val-ans**n |<;epsilon”。你知道吗

    “low”必须小于根,“high”必须大于根:这就是为什么low=-| val |

    您可以检查任何值u,(-u)**n<;u(u为负且指数为偶数时除外)

    高=最大值(| val |,1),因为如果| val |>;1,| val |**n>;| val |>;=val 如果| val |<;1,则根必须小于1

  3. 如果幂为偶数且值为负,则根不能为实(因为对于R中的任何x,x**2n都不能为负)

相关问题 更多 >