Quote:

>Hi guys,

> I'm really new to awk and I need to do some "simple"arithmetic

>calculations using awk.

>I know this is a very easy calculation but just can't figure it out on

>my own. I need some help.

>Whenever my "infile" contains a Zero (0) value in one of its field and

>it becomes a denominator

>in my simple arithmetic calculation, I always got this message:

>1 2 $3 awk: division by zero

>input record number 1, file 1.1

>source line number 1

> What I want to happen in my script is that even though I have

>Zero (0) in one or more

>in the field of my input file and it's being used in my awk

>caluculations (addition, subtraction,

>div., mult. ...) the result will still give me a Zero (0) value not the

>message shown above..

>My shell script:

>#!/bin/ksh

>awk '{print $1"\t", $2"\t", "$"$3"\t",

>((($3-(($2+$6)/$4))+$1)/2)*100"\t", $4"\t", $5"\t"}' infile

>|

>|___ 4th field contains Zero numbers (0)

>My infile:

>1 2 3 0 5 6 7 8 9 10

>2 3 0 0 6 7 8 9 10 1

>3 4 5 0 7 8 9 10 1 2

>4 5 6 0 8 9 10 1 2 3

>5 6 7 0 9 10 1 2 3 4

> Any suggestions on how to do this? Just send me an email or

>you can answer me by posting in

>this group.

> Thank you very much.

>Albert

Division by zero is not a valid mathematical operation. I'll skip the

theoretical deatils and just say that no programming language will allow you

to divide anything by zero.

If you want a zero result for any expression that involves dividing by zero,

you either need to define a function that replaces the division operator, or

you need to catch zero denominators and convert them to something very, very

large.

First alternative (note that I converted your print w/concatenation to

printf):

function div(numer, denom) { return denom == 0 ? 0 : numer / denom }

{ printf("%g\t %g\t $%g\t %g\t %g\t %g\t\n",

$1, $2, $3, (($3 - div($2 + $6, $4) + $1) / 2) * 100, $4, $5) }

which produces the following output given your infile

1 2 $3 200 0 5

2 3 $0 100 0 6

3 4 $5 400 0 7

4 5 $6 500 0 8

5 6 $7 600 0 9

Second alternative (also with print converted to printf):

{ printf("%g\t %g\t $%g\t %g\t %g\t %g\t\n",

$1, $2, $3, (($3 - ($2 + $6) / ($4 == 0 ? 1e+100 : $4) + $1) / 2) * 100,

$4, $5) }

which produces the following output given your infile

1 2 $3 200 0 5

2 3 $0 100 0 6

3 4 $5 400 0 7

4 5 $6 500 0 8

5 6 $7 600 0 9

Both alternatives have points in their favor, but I think the first is

clearer.