gnuplot:如何对任意列表求和

问题描述 投票:0回答:2

对于 gnuplot,我有一个很大的(随机生成的)数字列表,我想将其用作总和中的索引。我该怎么做?

这就是我的意思。假设数字列表是

list = [81, 37, 53, 22, 72, 74, 44, 46, 96, 27]

我有一个功能

f(x,n) = cos(n*x)

我现在想在区间

(-pi,pi)
上绘制函数,该区间是
f(x,n)
的总和,因为
n
贯穿
list
中的数字。

range gnuplot
2个回答
2
投票

如果您可以控制列表的外观,请尝试以下操作:

num = 10

# Let the numbers be in a space separated string. 
# We can access the individual numbers with the word(string, index) function.
list = "81 37 53 22 72 74 44 46 96 27"

f(x,n) = cos(n*x)

set terminal pngcairo
set output "sum_cos.png"

set xrange [-pi:pi]
set samples 1000

# Build the plot command as a macro.
plt_cmd = ""
do for [n=1:num] {
   plt_cmd = sprintf("%s + f(x,%s)", plt_cmd, word(list,n))
}

# Check what we have done so far.
print plt_cmd

titlestring = "{/Symbol S} cos(n_i*x), i = 1 ...".num

# Finally plot the sum by evaluating the macro.
plot @plt_cmd title titlestring

这是结果:


1
投票

这是一个替代建议。 maij 答案中的宏可以简单地替换为 gnuplot 的

sum
函数(检查
help sum
)。 仅出于说明目的,我选择了不同的函数、不同的列表和不同的范围,以显示
sin(x)
的近似值。

。 。 .

脚本:(适用于 gnuplot>=4.6.0,2012 年 3 月)

### plot sum of function values
reset

list = "1 3 5 7 9 11 13"

f(x,n) = (-1)**int(n/2)*x**int(n)/int(n)!

mySum(x,N) = sum[j=1:N] f(x,word(list,j))

set xrange[-2*pi:2*pi]
set yrange[-2:2]
set samples 1000
set key top out

plot for [i=1:words(list)] mySum(x,i) w l ti sprintf("%d",i), \
     sin(x) w l lw 2 lc rgb "red"
### end of script

结果:

© www.soinside.com 2019 - 2024. All rights reserved.