python功能找到根(或零)与真实根epsilon的距离最小

时间:2015-05-17 14:32:19

标签: python function zero epsilon

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

public class Main {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InterruptedException{      
        MyObjectInterface myobj = new MyObject();       
        System.out.println(myobj.getHelloMessage());
        }

}

我们必须从这开始:

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 ##

(对不起我的英文)

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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