jeffrbauer
jeffrbauer

Reputation: 125

AWK division by zero error

I'm getting a division by 0 error from my awk command. I'm not sure what is causing this as the result should not be 0.

In this case it should be printing 1.11557887 from 1.7229/1.5444.

Could it be a problem with how I assigned the variables?

This is my script:

#!/usr/bin/awk -f

FNR == 22 { measC = $2 }
FNR == 23 { refC = $2 }
factorC = refC / measC
{ print factorC }

It returns:

/usr/bin/awk: division by zero
 input record number 1, file 1.txt
 source line number 5

This is what my input data looks like:

#!xxx x
# x x x x x x
# x: x x
# x: x x
# x: x x x x x
# (x) x x, x x x, x.
x: x x x x
x: 3.0.0
x: x
x: 0
x: x x
x: 0
x: x x
x: x
x: 0
x: 0
x: 2
x: x x x
x: x
x: 1
x: 4
origmax: 1.5444 1.5188 1.0221 1.4932
currentmax: 1.7229 1.6888 1.1069 1.6238

Upvotes: 1

Views: 1711

Answers (2)

ghoti
ghoti

Reputation: 46816

Your script says:

FNR == 22 { measC = $2 }

So ... when only, say, five lines of your input file have been read by this awk script, what is the value of measC?

I'll tell you a secret. It will be zero. Because nothing has assigned anything else to measC yet.

Also, your line:

factorC = refC / measC

is outside the block, so it's being used to evaluate whether the { print factorC } should be run. And because it's a condition, it gets run for every line. And wouldn't you know it, before line 22, measC is 0.

I don't understand the data or the output, so I don't know what measC should be, if anything.

What are you trying to achieve with this?

Upvotes: 2

rob mayoff
rob mayoff

Reputation: 385500

Because you put factorC = refC / measC outside of a block, awk thinks you want to use that expression as a pattern. So it evaluates that expression for each line of input. On the first line of input, measC hasn't been defined yet, so it defaults to zero.

I think you want this:

#!/usr/bin/awk -f

FNR == 22 { measC = $2 }
FNR == 23 { refC = $2 }
END {
    factorC = refC / measC
    print factorC
}

or this:

#!/usr/bin/awk -f

FNR == 22 { measC = $2 }
FNR == 23 {
    refC = $2
    factorC = refC / measC
    print factorC
}

Upvotes: 5

Related Questions