在bash循环中使用对数(浮点)增量

时间:2014-07-15 12:54:21

标签: bash loops floating-point

我有这个bash脚本基本上运行c模拟./infosimul mu num

其中参数线性增加,它们只取整数。

mu=1
num=0
while test $num -le 6;do
    mkdir $num
    cd $num
    while test $mu -le 200; do
            ../infosimul "$num" "$mu" 
            mu=$((mu+3))
        done
    mu=1
    cd ../
    num=$((num+1))
done

我希望μ参数在0.01,0.03,0.09,0.1,0.3,0.9,1,3,9,10或其他不完全是整数序列的集合中增加。

谢谢!

3 个答案:

答案 0 :(得分:3)

使用此技巧:循环遍历序列1 3 9

使用bc计算mu

mu=$(echo "scale=2; $val*$factor" | bc)

factor=0.01开始,在循环上面的序列后将其乘以10:

factor=$(echo "scale=2; $factor*10" | bc)

答案 1 :(得分:0)

这就是bash:

#!/bin/bash

mu=$1 num=$2

function is_le {
    local A1 A2 B1 B2

    if [[ $1 == *.* ]]; then
        A1=${1%%.*}
        A2=${1##*.}
    else
        A1=$1
        A2=0
    fi

    if [[ $2 == *.* ]]; then
        B1=${2%%.*}
        B2=${2##*.}
    else
        B1=$2
        B2=0
    fi

    (( L = ${#A2} > ${#B2} ? ${#A2} : ${#B2} ))

    A2=$A2'00000000000000000000'; A2=1${A2:0:L}
    B2=$B2'00000000000000000000'; B2=1${B2:0:L}

    (( A1 == B1 ? A2 <= B2 : A1 < B1 ))
}

for (( ; num <= 6; ++num )); do
    mkdir "$num" && pushd "$num" >/dev/null || continue
    while is_le "$mu" 200; do
        ../infosimul "$num" "$mu" 
        mu=$(( ${mu%.*} + 3 )).${mu#*.}
    done
    popd > /dev/null
done

答案 2 :(得分:0)

这是一种相当简单的方法:

#!/bin/bash
j=1
k=-2       # We are going to raise 10 to this power
num=1
while : 
do
   mu=$(echo "scale=2;$j*10^$k"|bc)
   echo ../infosimul "$num" "$mu" 
   [[ j -eq 1 ]] && j=2
   [[ j -eq 3 ]] && j=8
   [[ j -eq 9 ]] && j=0 && ((k++))
   ((j++))
   ((num++))
done

<强>输出

../infosimul 1 .01
../infosimul 2 .03
../infosimul 3 .09
../infosimul 4 .10
../infosimul 5 .30
../infosimul 6 .90
../infosimul 7 1
../infosimul 8 3
../infosimul 9 9
../infosimul 10 10
../infosimul 11 30
../infosimul 12 90
../infosimul 13 100
../infosimul 14 300
../infosimul 15 900