在 perl/awk 中使用 shell 脚本计算平方和

Ram*_*esh 3 awk perl

我有 2 个文件,如下所示。

文件 1

0.34
0.27
0.32
Run Code Online (Sandbox Code Playgroud)

文件 2

0.15
0.21
0.15
Run Code Online (Sandbox Code Playgroud)

现在,我想计算每列之间的平方和。例如,

[(0.34 - 0.15)^2 + (0.27 - 0.21)^2 + (0.32 - 0.15)^2 ] / 3
Run Code Online (Sandbox Code Playgroud)

其中3是文件中的总行数。我将在两个文件中使用相同数量的行。

我想出了下面的 bash 脚本,它运行得非常好,但我想知道是否还有其他更简单的方法。

#! /bin/bash   
sum=0.0
while true; do
  read -r lineA <&3
  read -r lineB <&4
  if [ -z "$lineA" -o -z "$lineB" ]; then
    break
  fi
diff=$(bc <<< "scale=5; $lineA - $lineB")
square=$(bc <<< "scale=5; $diff*$diff")
sum=$(bc <<< "scale=5; $sum+$square")
done 3<file1 4<file2
filelen=`wc -l file1 | cut -f1 -d' '`
final=$(bc <<< "scale=5; $sum/$filelen")
echo "$final"
Run Code Online (Sandbox Code Playgroud)

awk或 中有更简单的方法perl吗?

编辑

我的输入文件中有 200 万行,输入文件实际上包含如下科学数字。

3.59564e-185
Run Code Online (Sandbox Code Playgroud)

我的脚本以及建议的答案在科学数字上都失败了。但是,当我将科学数字更改为10^符号时,我可以使问题中的脚本起作用。

我转换了我的输入文件,如下所示。

sed -e 's/[eE]+*/\*10\^/' file1 > file1_converted
sed -e 's/[eE]+*/\*10\^/' file2 > file2_converted
Run Code Online (Sandbox Code Playgroud)

现在,建议的 2 个答案失败给我的错误消息为Nan. 我的脚本似乎可以工作,但是对于 200 万行,执行时间很长。

有什么有效的方法可以使它工作吗?

iru*_*var 7

一种使用方法,paste因为您的文件具有相同的行数。

paste file1 file2 | awk '{s += ($1-$2)^2}; END{print (s+0)/NR}'
0.0228667
Run Code Online (Sandbox Code Playgroud)