计算f(x)和g(x)之间在极限范围a和b内的交点(x,y)

2024-04-18 20:29:52 发布

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

输入(来自文件):

x^2-x+2,
x^3-1,
-2 2

期望输出:

intersection: (1.5747,2.9051)

我需要使用Newton-Rephson算法计算两个数学函数之间的x,y坐标交点,首先,我从文件中输入,然后使用func_sum计算两个函数fg,并将h函数(res of fg)发送到NR函数以找到根。我不确定我是否做对了,我正在努力找到解决办法

import random

def diff(f):
    ''' returns the numeric derivative of f '''
    h = 0.000001
    return (lambda x: (f(x+h)-f(x))/h)

def NR(f, epsilon=10**(-10), n=100):
    ''' finds an approximation to a root of
    f using the Newton Raphson method '''
    deriv = diff(f)
    x0 = random.uniform(-10, 10)
    while (abs(deriv(x0))<epsilon):
        x0 = random.uniform(-10, 10)
    x=x0; y=f(x); count=1
    print("{0}. x={1}, f(x)={2}".format(count,x,y))
    while(abs(y) > epsilon and count <= n):
        count += 1
        y=f(x)
        x = x - y/deriv(x)
        print("{0}. x={1}, f(x)={2}".format(count,x,y))
    if count > n:
        return None
    return (lambda a,b : x in range(a,b))

def func_sum(f_Func, g_Func):
    ''' function calculate the sum of f and g '''
    def h(x):
        return f_Func(x) + g_Func(x)
    return h

def main():
    f=open('input.txt','r')
    line=f.read().split('\n')
    f_Func = eval('lambda x:'+ line[0]) # f(x)
    g_Func = eval('lambda x:'+ line[1]) # g(x)
    h_Func = func_sum(f_Func,g_Func)
    # f(h) = f(x)+ g(x)
    limts = line[2].split()
    a = int(limts[0]) ; b = int(limts[1]) # a b are limits
    print('intersection: ', NR(h_Func)(a,b))

main()

Tags: ofthelambda函数returndefcountline