简体   繁体   English

浮点数组bash的最小值和最大值

[英]min and max of float array bash

I have an array of floats in bash: eg:我在 bash 中有一组浮点数:例如:

array(1.0002, 1.00232, 1.3222, ....)

I want to find the maximum and the minimum element of the array using bash.我想使用 bash 找到数组的最大和最小元素。 The problem with this is that I have float elements that are not quite supported in bash.这样做的问题是我的浮动元素在 bash 中不太受支持。

I have tried for example:例如,我尝试过:

IFS=$'\n'
echo "${ar[*]}" | sort -nr | head -n1

but it does not work for floats.但它不适用于花车。

What is the best way to do this ?做这个的最好方式是什么 ?

There are probably many ways and I don't claim the two following are " the best ".可能有很多方法,我不认为以下两种是“最好的”。

You could use a calculator that supports floats, like bc , for instance:您可以使用支持浮点数的计算器,例如bc

max="${array[0]}"
min="${array[0]}"
for v in "${a[@]}"; do
  max=$(echo "if($v>$max) $v else $max" | bc)
  min=$(echo "if($v<$min) $v else $min" | bc)
done
echo "max=$max"
echo "min=$min"

awk also supports floats, so the following would do the same: awk也支持浮点数,所以下面的代码也是一样的:

printf '%s\n' "${array[@]}" | \
awk '$1>max||NR==1 {max=$1}
     $1<min||NR==1 {min=$1}
     END {print "max=" max; print "min=" min}'
$array=(1.0002 1.00232 1.3222)        
$printf "%s\n" "${array[@]}" | sort -rn | head -n1        
1.3222          
$ printf "%s\n" "${array[@]}" | sort -rn | tail -n1  
1.0002  
#Tried with %s or %f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM