1

I want to raise a fraction (fraction is calculated on first loop) to a decimal power (second loop), however, I always get 1 as a result. I want to store the output of the second loop in an array as well. Any ideas how to work around this? Thank you!

#
# vector of vertical pressure levels
levs=($(seq 200.0 50.0 900.0))
printf "%s\n" "${levs[@]}"
#
# exponent for dry air
rho=$(bc -l <<<'e(l(0.0819)*0.5)')
echo $rho
#
# calculate fraction of P_surf/P_i from Poisson equation for each vertical pressure level
val3=()
#
for i in "${levs[@]}"
 do
   echo $i
   val3+=($(bc -l <<<"1000.0/$i"))
   echo "$val3"
 done
printf "%s\n" "${val3[@]}"
#
# raise fraction of P_surf/P_i to the rho power for dry air (#bc <<< "2 ^ 3")
pow=()
#
for j in "${val3[@]}"
 do
   echo $j
   echo $rho
   pow+=($(bc <<<"$j^rho"))
   #echo $((i*rho))
   echo "$pow"
 done
# 
1

There are a couple of problems associated with your attempt. The immediate problem being using rho as a literal string when raising it as a power constant to bc

bc <<<"$j ^ $rho"

Even with that the code does not work, bc does not take fractional numbers for exponents. You get an error non-zero scale in exponent.

You can use awk (tested on GNU variant) for the same and apply the equal precision formatting as

awk -v base="$j" -v xp="$rho" 'BEGIN{ printf "%.20f", base ** xp }'
2
  • 1
    The OP already uses e(l(0.0819)*0.5) in place of 0.0819 ^ 0.5 (where they could have used sqrt(0.0819)), so here, that could just as well use e(l($j)*$rho) – Stéphane Chazelas Oct 9 '19 at 10:50
  • Thank you, Inian and Stephane! – Maria Karypidou Oct 9 '19 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.