Operating System - HP-UX
1753901 Members
8776 Online
108810 Solutions
New Discussion юеВ

Re: Floting point operation

 
SOLVED
Go to solution
Leo The Cat
Regular Advisor

Floting point operation

Hi Guys

Here my script

for instance in $(.........)
do

(( mySum= 0.0000 ))
#
for PID in $(.....)
do
lecture=$( here a call to a function returning float value )
echo $instance $lecture
(( mySum = $mySum + $lecture ))
done
print "mySum=" $mySum

done

and the result:

(Example)

opclmqa1 15.0
opclmqa1 0.1
opclmqa1 0.2
opclmqa1 0.0

mySum= 15

I should have 15.3

why ? and how to fix ?

Bests Regards
Den
7 REPLIES 7
James R. Ferguson
Acclaimed Contributor

Re: Floting point operation

Hi Den:

Most shells only support integer arithmetic.

# X=100;Y=25;((Z=X/Y));echo $Z

If you want to incorporate real numbers, 'bc' provides a convenient vehicle. Choose the 'scale' to set the precision you want:

# X=1;Y=8;echo "scale=3\n $X/$Y"|bc

You can also leverage 'awk' and couple it with 'printf' to format output, including moving to a different number base:

# X=1;Y=8;echo "$X $Y"|awk '{printf "%.4f\n",$1/$2}'

# X=7;Y=8;echo "$X $Y"|awk '{printf "%4x\n",$1+$2}'

The standard Korn shell in HP-UX is Korn88 and does integer arithmetic. However, if you use the Korn93 (found in HP-UX as '/usr/dt/bin/dtksh') shell, its 'typeset' allows a more direct approach to real numbers:

#!/usr/dt/bin/dtksh
typeset -F R1
typeset -F3 R2
typeset -E R3
let R1=1/8
echo $R1
let R2=1/8
echo $R2
let R3=1/8
echo $R3
exit 0

Regards!

...JRF...
Leo The Cat
Regular Advisor

Re: Floting point operation

Hi James

HUmm, but how to do a sum in this case ? it seems difficult like this.

Have a nice end day
Thanks James.
James R. Ferguson
Acclaimed Contributor
Solution

Re: Floting point operation

HI (again) Den:

One example, using your data:

# cat ./info
opclmqa1 15.0
opclmqa1 0.1
opclmqa1 0.2
opclmqa1 0.0

# awk '{SUM+=$2};END{printf "%6.1f\n",SUM}' ./info
15.3

Regards!

...JRF...
Leo The Cat
Regular Advisor

Re: Floting point operation

Arrr. Sorry I have reopen it.

Finally I prefer to build my list
and then I'm able to have this ...

echo $a
1.1 1.0 23.10 1.4 0.8 0.0 0.0

How to have the sum of all float number in my variable ?

Bests regards
Denis A. Jeanneret
Leo The Cat
Regular Advisor

Re: Floting point operation

It's ok

With a pipe against awk '{s=0; for (i=1; i<=NF; i++) s=s+$i; print s}'

Thanks James, have a nice week end
Bests regards
Den

Leo The Cat
Regular Advisor

Re: Floting point operation

James Solution is efficient with my small addons.
Dennis Handly
Acclaimed Contributor

Re: Floting point operation

>How to have the sum of all float number in my variable?

Instead of looping in awk, you can loop in the shell:
for i in $a; do echo $i; done |
awk '{SUM+=$1};END{printf "%6.1f\n",SUM}'