提问人:FIG 提问时间:3/19/2023 更新时间:3/19/2023 访问量:29
我正在尝试将我的代码转换为输出下图,我想知道到达那里的步骤
I'm trying to convert my code to output the following graph and I'm wondering the steps to take to get there
问:
我一直在尝试使用 Matplotlib 修改 Python 代码,运行时作为间隔计数 N 的函数,通过将 1/2 间隔计数 n 从 10^1 的量级更改为 10^9 的 10 次幂。
并绘制了两条不同颜色的线:一条显示串行计算产生的运行时,另一条显示使用 Python 多处理模块进行并行计算产生的运行时。
我试图让它看起来像这样,但我不知道在 Sublime Text 编辑器中这样做的步骤。
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")
答: 暂无答案
评论
plt