我正在尝试将我的代码转换为输出下图,我想知道到达那里的步骤

I'm trying to convert my code to output the following graph and I'm wondering the steps to take to get there

提问人:FIG 提问时间:3/19/2023 更新时间:3/19/2023 访问量:29

问:

我一直在尝试使用 Matplotlib 修改 Python 代码,运行时作为间隔计数 N 的函数,通过将 1/2 间隔计数 n 从 10^1 的量级更改为 10^9 的 10 次幂。

并绘制了两条不同颜色的线:一条显示串行计算产生的运行时,另一条显示使用 Python 多处理模块进行并行计算产生的运行时。

我试图让它看起来像这样,但我不知道在 Sublime Text 编辑器中这样做的步骤。

WANTED RESULT

import math
import numpy as np
import time
import multiprocessing as mp
import matplotlib.pyplot as plt

def f(x):
    return math.acos(math.cos(x) / (1 + 2 * math.cos(x)))

n = int(1e1)  # number of intervals must be even\n"
b = math.pi / 2
a = 0
h = (b - a) / n
exact = math.pi ** 2 / 16

def g(j):
    global a
    global h
    return (f(a + (2 * j - 2) * h) + 4 * f(a + (2 * j - 1) * h) + f(a + (2 * j) * h))

if __name__ == '__main__':
    mp.freeze_support()  # needed for Windows

    print(f"subinterval half-length (discretization step) h = {h}")

    N = int(n / 2);
    print(f"subintervals N = {N}")

    pool = mp.Pool(processes=mp.cpu_count())
    istart = 0
    iend = N

    print(f"istart: {istart}, iend: {iend}\n")

    start_time = time.time()
    p = [pool.map(g, range(istart+1,iend+1))]
    P = (h / 3) * np.sum(p)
    elapsedTime = time.time() - start_time;
    print(f"parallel: approximation: {P}, exact: {exact}, error: {np.abs(P - exact)}, intervals: {N}, runtime: {elapsedTime} s, threads: {mp.cpu_count()}\n")
    
    start_time = time.time()
    S = 0
    for j in range(istart+1,iend+1):
        S += f(a + (2 * j - 2) * h) + 4 * f(a + (2 * j - 1) * h) + f(a + (2 * j) * h)
    S *= h / 3
    elapsedTime = time.time() - start_time;

    print(f"serial: approximation: {S}, exact: {exact}, error: {np.abs(S - exact)}, intervals: {N}, runtime: {elapsedTime} s")
python-3.x sublimetext3 sublime-text-plugin

评论

0赞 MattDMo 3/20/2023
那么问题出在哪里呢?你被困在哪里了?什么正在发生,不应该发生,或者什么没有发生,应该发生?你的代码甚至没有使用 ,所以难怪没有出现情节。plt

答: 暂无答案