0

所以它和python的练习我完全被卡住了!您在 [a,b] 中有一个随机函数,您已经知道 a 是负数,b 是正数,并且它只有一个根。真正的根是: -0.94564927392359,你必须做一个 def 来找到最接近真正根的根(或零),且差异eps最小。eps是 1e-8 或 1e-6。请注意,我们不知道真正的根,之前是一个例子来了解我们正在寻找的数字是关于什么的。我们也得到了上述内容:

import math

def fnc(x):
    """ This the function in which root we are looking for """
    global a, b, eps
    if not hasattr(fnc, "counter"):
        fnc.counter = 0
        fnc.maxtimes = (int)(0.1+math.ceil(math.log((b-a)/eps, 2.0)+2))
    if fnc.counter<fnc.maxtimes:
        fnc.counter += 1
        return x*x*x-x-0.1 
    else:
        return 0.0 ##

我们必须从这个开始:

def root(f, a, b, eps):

(对不起我的英语不好 )

4

2 回答 2

0

看看以下迭代将区间分割成 2 个等于然后选择允许的一半的启发式是否适合您。

def root(fnc, a, b, eps = 1e-8, maxtimes = None):
    if maxtimes == None: maxtimes = (int)(0.1+math.ceil(math.log((b-a)/eps, 2.0)+2))
    for counter in xrange(maxtimes+1) : # a was assumed negative and b positive
        if fnc(a) > -eps : return a, -fnc(a)
        if fnc(b) < eps : return b, fnc(b)
        new_bound = (a + b)/2.0
        print a, b, new_bound
        if fnc(new_bound) < 0 : a = new_bound
        else : b = new_bound
    return new_bound, min(-fnc(a),fnc(b))

接着

fnc = lambda x : x**3-x-0.1
result = root(fnc, 0, 2, 1e-6)
print "root = ", result[0], "error = ", result[1]
于 2015-05-17T17:48:49.527 回答
0

只是简单的平分:

from __future__ import division
import math

def func(x):
    return x*x*x-x-0.1

def sign(n):
    try:
        return n/abs(n)
    except ZeroDivisionError:
        return 0

def root(f, a, b, eps=1e-6):
    f_a = f(a)
    if abs(f_a) < eps:
        return a
    f_b = f(b)
    if abs(f_b) < eps:
        return b

    half = (b+a)/2
    f_half = f(half)

    if sign(f_half) != sign(f_a):
        return root(f, a, half, eps)
    else:
        return root(f, half, b, eps)

print root(func, -1.5, -0.5, 1e-8)  # -0.945649273694
于 2015-05-17T18:28:24.557 回答