Reputation: 11
I wan to know how to confirm that two integers in tcl are close to each other? In other words if the value difference between the two numbers is less or equal to 5, result is pass else FAIL.
can somebody tell me how to write it in tcl? or suggest me which operator i can use to achieve this.
Thanks, Kallesh
Upvotes: 1
Views: 6551
Reputation: 13252
The difference between two numbers a
and b
is equal to $a - $b
. This difference can be either negative or positive (or zero if they are equal), but to make the comparison easier you want the absolute value (magnitude) of the difference, i.e. the value disregarding sign. You get that by abs($a - $b)
. The only thing that remains to do is to compare it with 5: abs($a - $b) <= 5
.
The expr
command can take this expression as an argument and calculate a truth value: expr {abs($a - $b) <= 5}
will return either 1 if the comparison was calculated to be true, and 0 otherwise.
The if
command can take this expression and use it for algorithmic flow control, i.e. to decide which commands get invoked and which get skipped:
if {abs($a - $b) <= 5} {
# invoked if true
} else {
# invoked if false
}
Re: Donal's comment; in my original answer I made the elementary mistake of pasting in an invocation of expr
inside the condition to the if
statement. There is no need to do that, since the first argument to if
is implicitly evaluated as by the expr
command anyway. It won't do any harm to invoke expr
that way, but it will cause some snickering if someone sees it.
Upvotes: 1
Reputation: 137577
The abs
function computes the magnitude of a number, i.e., if it is negative it negates it. All you have to to then is look at the magnitude of the difference between the two integers and see if that is within the threshold that you care about.
if {abs($a - $b) <= 5} {
# Values are indeed "close enough"
}
This is a standard technique; it's very common when comparing floating point numbers (though a smaller “close enough” value is usually used; in that domain, it's usually called ε or epsilon).
Upvotes: 0