You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python导入外部文件后如何获取循环生成的全量数据?

How to Capture All Iteration Data from an Imported Python Module

The issue you're facing makes total sense—when you import the approx_derivative_sine.py module, the loop runs immediately, and each iteration overwrites variables like delta_x and calculated. By the time you access them, they only hold values from the last loop iteration.

Here are two straightforward solutions to get all the iteration data you need for your matplotlib plots:


This is the cleanest approach if you're allowed to edit the provided approx_derivative_sine.py file. We'll refactor it to collect all iteration data in a list and expose a function to return that data.

Updated approx_derivative_sine.py:

# This program is needed in Problem 6.5 Interpret output from a program.
from math import sin, cos, pi

def f(x):
    return sin(x)

def df_approx(f, x, delta_x):
    # Optional: keep this print if you still want to see the raw difference
    # print(delta_x, f(x+delta_x)- f(x))
    return (f(x+delta_x)-f(x))/delta_x
# return (f(x+delta_x)-f(x-delta_x))/(2*delta_x)  # alternative approximation

def get_iteration_results():
    x = pi/3
    iteration_data = []
    for n in range(1, 20):
        delta_x = 10**(-n)
        calculated = df_approx(f, x, delta_x)
        exact = cos(x)
        rel_err = abs(calculated - exact)/abs(exact)
        abs_err = abs(calculated - exact)
        
        # Store each iteration's data in a dictionary for easy access
        data_entry = {
            "n": n,
            "delta_x": delta_x,
            "df_approx": calculated,
            "df_exact": exact,
            "abs_error": abs_err,
            "rel_error": rel_err
        }
        iteration_data.append(data_entry)
        
        # Keep the original print statement if you want to see output when running the module directly
        print("delta_x: %e, df_approx: %13.10e, df_exact: %13.10e, abs_error: %e, rel_error: %e, n=%d" % 
              (delta_x, calculated, exact, abs_err, rel_err, n))
    
    return iteration_data

# Run the function automatically if the module is executed directly (not imported)
if __name__ == "__main__":
    get_iteration_results()

How to Use It in Your Code:

Now you can import the function and grab all the data at once, then extract the arrays you need for plotting:

from approx_derivative_sine import get_iteration_results
import matplotlib.pyplot as plt

def process_data_and_plot():
    # Get all iteration data
    all_data = get_iteration_results()
    
    # Extract individual arrays using list comprehensions
    n_values = [entry["n"] for entry in all_data]
    delta_x_values = [entry["delta_x"] for entry in all_data]
    approx_derivatives = [entry["df_approx"] for entry in all_data]
    absolute_errors = [entry["abs_error"] for entry in all_data]
    
    # Create your plots
    plt.figure(figsize=(12, 5))
    
    # Plot 1: Approximate vs Exact Derivative
    plt.subplot(1, 2, 1)
    plt.plot(n_values, approx_derivatives, marker="o", label="Approximate Value")
    plt.axhline(y=all_data[0]["df_exact"], color="r", linestyle="--", label="Exact Value")
    plt.xlabel("Iteration Number (n)")
    plt.ylabel("Derivative Value")
    plt.title("Sine Derivative Approximation Over Iterations")
    plt.legend()
    plt.grid(True)
    
    # Plot 2: Absolute Error vs Iteration
    plt.subplot(1, 2, 2)
    plt.plot(n_values, absolute_errors, marker="x", color="g")
    plt.xlabel("Iteration Number (n)")
    plt.ylabel("Absolute Error")
    plt.title("Absolute Error Trend")
    plt.grid(True)
    
    plt.tight_layout()
    plt.show()

process_data_and_plot()

Solution 2: Capture Output Without Modifying the Original Module

If you can't edit the provided approx_derivative_sine.py file (e.g., it's a fixed task resource), you can replicate the loop logic in your code using the module's functions and constants to collect data.

Re-Run the Loop Logic (Most Reliable):

import approx_derivative_sine as apx
import matplotlib.pyplot as plt

def collect_data_without_modifying_module():
    x = apx.pi / 3
    iteration_data = []
    
    # Replicate the loop from the module
    for n in range(1, 20):
        delta_x = 10**(-n)
        calculated = apx.df_approx(apx.f, x, delta_x)
        exact = apx.cos(x)
        rel_err = abs(calculated - exact) / abs(exact)
        abs_err = abs(calculated - exact)
        
        iteration_data.append({
            "n": n,
            "delta_x": delta_x,
            "df_approx": calculated,
            "abs_error": abs_err
        })
    
    return iteration_data

def plot_results():
    all_data = collect_data_without_modifying_module()
    
    # Extract arrays
    n_values = [d["n"] for d in all_data]
    delta_x_values = [d["delta_x"] for d in all_data]
    approx_derivatives = [d["df_approx"] for d in all_data]
    absolute_errors = [d["abs_error"] for d in all_data]
    
    # Plot absolute error vs delta_x (log scale highlights trends better!)
    plt.figure(figsize=(10, 6))
    plt.loglog(delta_x_values, absolute_errors, marker="s")
    plt.xlabel("delta_x (log scale)")
    plt.ylabel("Absolute Error (log scale)")
    plt.title("Absolute Error vs Delta_x")
    plt.grid(True, which="both", ls="-")
    plt.show()

plot_results()

Both approaches will give you full access to all 19 iterations of data, so you can create the matplotlib plots you need to analyze the approximation trends.

内容的提问来源于stack exchange,提问作者fredericoamigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 21:02:29