定点法函数不显示输出

问题描述 投票:0回答:1

我做了一个用于计算数值定点方法的函数,但是当我运行程序时没有输出。我只是看不出问题出在哪里,我尝试添加最大迭代,但仍然不起作用,或者当我尝试填充 fxI_values 时,它给了我一个索引错误:列表索引超出范围 xl 的值=1 误差=0.01

def fixedPoint(xL,error):
    xI=xL
    x0=xI
    
    xI_values=[]
    fxI_values=[]
    calc_error=[]

    while True:

        xI_values.append(xI)
        absError = abs(xI-x0)

       
        xI=fixedPoint_func(xI)
        
        calc_error.append(absError)

        # Check for convergence
        if absError <= error:
            break
        
 # Prepare data for tabulation
    table_data5 = []
    for j in range(len(xI_values)):
        iteration_number = j + 1
        table_data5.append([iteration_number, xI_values[j], fxI_values[j], calc_error[j]])

    # Print table
    headers = ["Iteration", "Xi", "g(Xi)", "Error"]
    print("Fixed Point Method :")
    print()
    print(tabulate(table_data5, headers=headers, floatfmt=".4f"))

    # Print a separator line
    print("-" * 100)
    print()  # Print an empty line for spacing

    return xI_values[-1]

python function math encoding numeric
1个回答
0
投票

问题

你调用这个函数吗?

当我调用该函数时,它向我显示此错误。

Traceback (most recent call last):
  File "/home/deepesh/Development/public/hackthon/graph-e-ton/mr_omd/main.py", line 45, in <module>
    fixedPoint(1, 0.001)
  File "/home/deepesh/Development/public/hackthon/graph-e-ton/mr_omd/main.py", line 30, in fixedPoint
    table_data5.append([iteration_number, xI_values[j], fxI_values[j], calc_error[j]])
IndexError: list index out of range

重新创建代码

import math

def function(x):
    return math.cos(x) - 3 * x + 1

def gfunction(x):
    return (1 + math.cos(x)) / 3
    
def fixed_point(x, error):
    step = 0
    x0 = x
    print("Step \t x0 \t\t f(x0) \t\t x1 \t\t f(x1)")
    
    while True:
        x1 = gfunction(x0)
        step += 1
        print(f"{step} \t {x0} \t {function(x0)} \t {x1} \t {function(x1)}")
        
        if abs(function(x1)) < error:
            print(f"Root is: {x1}")
            return
        
        x0 = x1



error = float(input("Enter allowed error : "))
x0 = float(input("Enter initial guess: "))
    
# Calling the function    
fixed_point(x0, error)

重新创建代码的灵感

我可以通过以下方式更好地帮助您:请告诉我所提供的解决方案是否有帮助。如果没有,请在评论中描述您的问题,并让我知道您期望的输出。

© www.soinside.com 2019 - 2024. All rights reserved.