【问题标题】:How can I write a bash script to calculate an integral?如何编写 bash 脚本来计算积分?
【发布时间】:2019-04-24 14:53:26
【问题描述】:

我想写一个 bash 脚本。该脚本必须读取包含两列的文件。它必须读取第一列的第一行(比如说 x1)。然后它必须读取第二列的第二行(比如 v2)和第一行(比如 v1)。然后它必须计算 x1-y1 的值,其中 y1=v2-v1。所有这些都针对第一列的每一行直到文件末尾,并将所有值返回到输出。

就我个人和基本经验而言,真正的困难是按照我的描述来调用变量。正如标题中所写,该操作是评估积分。

如果你有任何建议,比如用 python 编写相同的脚本,因为更容易,这对我来说很好。

真的谢谢大家。

更新 我尝试使用 Python。我在获取迭代脚本时遇到了一些困难。这就是我所拥有的:

import sys
import numpy as np

for i in range(0, 99):
xvals=np.loadtxt("pos{}.txt".format(i), float)
yvals=np.loadtxt("forc{}.txt".format(i), float)

if (len(xvals) != len(yvals)):
print ("Error bla bla")
sys.exit()

integr = 0

for i in range (1, len(xvals), 1):
integr = integr + yvals[i]*(xvals[i] - xvals[i-1])

integr=np.savetxt("work{}.txt".format(i), integr.reshape(1,), fmt='%1.5f')

再次感谢大家。

【问题讨论】:

  • 你能展示一个示例输入吗?另外,您尝试了哪些方法,又是如何失败的?
  • 我想你知道bash 本身不能处理浮点数,即非整数值......

标签: bash sum integral


【解决方案1】:

我认为您需要查看 bash 数组,因此这里有一个示例可以帮助您入门:

#!/bin/bash

# Declare two arrays
declare -a x
declare -a y

# Read two values from each line of input file and append to arrays "x" and "y"
while read c1 c2 ; do
   x+=($c1)
   y+=($c2)
   echo "read c1=$c1 and c2=$c2"
   # Demonstrate some maths - a simple difference
   ((diff=c2-c1))
   echo "difference: $diff"
done < file.txt

# Print a couple of elements to see how to access them
echo "x[0]=${x[0]}"
echo "y[2]=${y[2]}"

如果我将其用作file.txt

10 20
11 21
12 22

我明白了:

read c1=10 and c2=20
difference: 10
read c1=11 and c2=21
difference: 10
read c1=12 and c2=22
difference: 10
x[0]=10
y[2]=22

希望这足以让您入门。正如我在 cmets 中提到的,bash 无法进行浮点数学运算,因此如果您的数据是浮点数,您可能需要使用 awkPython

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2020-06-09
    • 2013-09-29
    • 2017-03-17
    • 1970-01-01
    • 2010-11-26
    • 2012-09-03
    相关资源
    最近更新 更多