【问题标题】:python fuction finding root( or zero) with minimum distance from real root epsilonpython函数找到与真实根epsilon最小距离的根(或零)
【发布时间】:2015-07-29 01:19:50
【问题描述】:

所以它和 python 的练习我完全被卡住了!您在 [a,b] 中有一个随机函数,您已经知道 a 是负数,b 是正数,并且它只有一个根。 真正的根是:-0.94564927392359,你必须做一个 def 将找到最接近真实根且差异最小的根(或零)epseps 为 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):

(对不起我的英语)

【问题讨论】:

  • 我认为如果没有一些附加条件(例如,[[Lipschitz Continuity]](en.wikipedia.org/wiki/Lipschitz_continuity),这是不可能的。
  • @AmiTavory 我相信,OP 已经发布了基础数值分析课程的作业

标签: python function zero epsilon


【解决方案1】:

只是简单的平分:

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

【讨论】:

    【解决方案2】:

    看看下面的迭代将区间分割成 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]
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      相关资源
      最近更新 更多