我正在尝试解决以下问题.
I am trying to solve the following question.
这是我编写的代码
import numpy as np import math sum = 4 while sum <= 13: b = 10**(-sum) x = (math.sqrt(9+b)-3)/(b) print(x) sum +=1给出以下结果
0.16666620370475727 0.1666666203714584 0.1666666618049817 0.1666666671340522 0.1666666804567285 0.1666666804567285 0.1666666804567285 0.1666666804567285 0.16653345369377348 0.16431300764452317我不确定我的代码是否正确.当我在Wolfram的原始方程式中将 n 的13插入时,我得到了一些不同的东西.我认为随着距离13越来越近,它将接近0.1666666.
I am not sure if my code is correct or not. When I plug in 13 for n into the original equation in wolfram I am getting something different. I figured as it got closer to 13 it would approach 0.1666666.
我又如何从中制作图表?我想这是观察结果的最好方法.
Also how would I make a graph from this? I guess this would be the best way to observe my results.
推荐答案下面是与情节一起的完整解决方案.说明: np.logspace(4,13,10)将 x 的值创建为10 ^(4),10 ^(5),10 ^(6)... 10 ^(13).您将其输出取反值,以得到所需的x点为10 ^(-4),10 ^(-5),10 ^(-6)... 10 ^(-13).然后,您可以遍历这些x值并求解方程式.将每个x的输出值保存在列表中,然后将其绘制出来.
Here is a complete solution together with the plot. Explanation: np.logspace(4, 13, 10) creates the values of x as 10^(4), 10^(5), 10^(6)... 10^(13). You take the inverse of its output to get your desired x-points as 10^(-4), 10^(-5), 10^(-6)... 10^(-13). You then loop over these x-values and solve for your equation. You save the output value for each x in a list and then plot it.
还有其他矢量化方法,而无需创建循环.但这应该可以帮助您入门.
There are other vectorized approaches without having to create a loop. But this should get you started.
import numpy as np import math import matplotlib.pyplot as plt xmesh = 1./np.logspace(4, 13, 10) result = [] for x in xmesh: elem = (math.sqrt(9+x)-3)/(x) # removed 'b' because xmesh is already inverse result.append(elem) # Adds each element to the list for later plotting plt.semilogx(xmesh, result, '-bo') # Uses a logarithmic x-axis plt.gca().invert_xaxis() # Inverts the x-axis because you want it so as per comments plt.xlabel('1/x', fontsize=16) plt.ylabel('y', fontsize=16) plt.show()输出
使用您的代码
以下是如何在无需大量修改的情况下使用您的代码使其工作
Following is how to make it work using your code without much modification
import numpy as np import math import matplotlib.pyplot as plt sum = 4 xmesh = 1./np.logspace(4, 13, 10) result = [] while sum <= 13: b = 10**(-sum) x = (math.sqrt(9+b)-3)/(b) result.append(x) sum +=1 plt.semilogx(xmesh, result, '-bo') plt.gca().invert_xaxis() plt.xlabel('1/x', fontsize=16) plt.ylabel('y', fontsize=16) plt.show()矢量化方法
import numpy as np xmesh = 1./np.logspace(4, 13, 10) result = (np.sqrt(9+xmesh)-3)/(xmesh) # No need to loop. Used `np.sqrt` plt.semilogx(xmesh, result, '-bo') plt.gca().invert_xaxis()更多推荐
使用python解释结果
发布评论