绘制数学求和函数(Alpine1)

2024-10-01 07:10:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望使用Python绘制Alpine1函数。函数如下所示:

Alp(x_1,…,x_n)=∑_(i=1)^n【| x|i*sin(x|i)+1.01x|i】

ALpine1

所以函数求和(from i=1 to n)的倒数xi*sin(xi) +1.01xi。如果没有求和,Python中的函数如下所示:

def f(x):
   return (abs(x * np.sin(x) + 1.01 * x))
<席>这里,我用X代替XI,求和被省略。如何正确实现求和from i=1 to n?简单地使用sum()只给出一个值,而我需要一个数组

我想我需要朝着一种for i in range(1,...)类型的东西的方向看,但我还没有弄明白

提前感谢能帮助我的人


Tags: to函数fromreturndefnp绘制abs
3条回答

Python和其他语言中的求和通常使用for循环实现。 在上面的公式中,您正在循环所有元素x1,x2,x3。。。xn

现在,为了存储这些值,我们使用一个数组,或者在python中使用一个列表,它基本上是一个数据集合(顺序很重要)

x = [x_1, x_2, x_3 ... x_n]

这将是函数f(x)的输入。为了循环x中的所有值,我们使用语法

for x_i in x:
    print(x_i)

这将打印所有值,即x_1、x_2、x_3。。。x_n

现在,我们将声明一个变量summation = 0,并存储所需的计算值,正如您在其中的问题中所提到的,并在循环遍历所有x值后返回求和值

summation = 0
for x_i in x:
    summation = summation + (abs(x_i * np.sin(x_i) + 1.01 * x_i))
#Note we returned the summation without the indentation
#so that it is out of the for loop.
return summation

可以使用np.sum获取数组的和。Numpy的broadcasting和向量化注意将所有元素分别计算,然后求和

以下是一个例子:

import numpy as np

def alpine1(xis):
    return np.sum(np.abs(xis * np.sin(xis) + 1.01 * xis))

xis = np.array([1, 2, 3])
print(alpine1(xis)) # 9.143425862638862

正如您的帖子提到的绘图,下面是Alpine1函数的热图如何应用于两个值:

import numpy as np
import matplotlib.pyplot as plt

def alpine1(xis):
    return np.sum(np.abs(xis * np.sin(xis) + 1.01 * xis))

x1, x2 = np.meshgrid(np.linspace(-10, 10, 500), np.linspace(-10, 10, 500))
z = np.apply_along_axis(alpine1, -1, np.dstack([x1, x2]))
plt.pcolormesh(x1, x2, z, cmap='inferno')
plt.colorbar()
plt.show()

example plot

这是3D曲面(z = Alpine1(x1, x2))的外观:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def alpine1(xis):
    return np.sum(np.abs(xis * np.sin(xis) + 1.01 * xis))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x1, x2 = np.meshgrid(np.linspace(-10, 10, 500), np.linspace(-10, 10, 500))
z = np.apply_along_axis(alpine1, -1, np.dstack([x1, x2]))

surf = ax.plot_surface(x1, x2, z, cmap='inferno', edgecolor='none')
fig.colorbar(surf)
plt.show()

3D surface plot

谢谢,我想我已经明白多了

实际上我在想另一件事。Alpine1是一个n维函数,因此假设我想采用函数直接产生的“2D版本”:

def Alpine(x1, x2): 
return (np.abs(x1 * np.sin(x1) + 1.01 * x1)+ np.abs(x2 * np.sin(x2) + 1.01 * x2))

现在我该如何绘制它?仍然需要两个变量(实际上是数组)(x1和x2),但我认为np.apply_along_axis只适用于1d。我该怎么处理

也许用x表示x1,用y表示x2更容易理解

相关问题 更多 >