News:

  • June 08, 2026, 03:08:46 AM

Login with username, password and session length

Author Topic: Using IF in MATH  (Read 8572 times)

hdsi44

  • Newbie
  • *
  • Posts: 4
Using IF in MATH
« on: June 17, 2021, 01:44:01 PM »
I'm having a little trouble using IF in the MATH box.  I'm trying to avoid a divide by zero error by using this statement:
IF(MHR2 > 0, TOREAL(T27.Acc / 1000) / (MHR2 * 6), 0)  or:
IF(MHR2 == 0, 0, TOREAL(T27.Acc / 1000) / (MHR2 * 6))
Both ways result in a divide by zero error.  What am I doing wrong?

Mike Nash

  • Hero Member
  • *****
  • Posts: 652
Re: Using IF in MATH
« Reply #1 on: June 17, 2021, 01:49:50 PM »
The equation is evaluated even though you are trying to check for zero first, so you get the error. Just add 0.0000001 or something to MHR2 where it could be an issue. E.g. IF(MHR2 > 0, TOREAL(T27.Acc / 1000) / ((MHR2+0.0000001) * 6), 0)

You could possibly get rid of the MHR2>0 test then.

hdsi44

  • Newbie
  • *
  • Posts: 4
Re: Using IF in MATH
« Reply #2 on: June 17, 2021, 02:13:20 PM »
Interesting, I would not have thought it worked like that.  Your expression will give a very large result.  I'll just use ladder logic and two different math boxes.

Thanks.

BobO

  • Host Moderator
  • Hero Member
  • *****
  • Posts: 6158
  • Yes Pinky, Do-more will control the world!
Re: Using IF in MATH
« Reply #3 on: June 17, 2021, 03:10:46 PM »
Interesting, I would not have thought it worked like that.  Your expression will give a very large result.  I'll just use ladder logic and two different math boxes.

Thanks.

IF(cond, value1, value2) is simply a function, rather than branches in execution. The normal high level language construct IF(cond1){ return value1; } else { return value2; } is a significantly more difficult thing to add to the MATH box. We do hope to have a high level language eventually, but the MATH box is comparatively basic.
"It has recently come to our attention that users spend 95% of their time using 5% of the available features. That might be relevant." -BobO

hdsi44

  • Newbie
  • *
  • Posts: 4
Re: Using IF in MATH
« Reply #4 on: June 17, 2021, 03:44:37 PM »
Thanks for the explanation, that makes sense.

Mike Nash

  • Hero Member
  • *****
  • Posts: 652
Re: Using IF in MATH
« Reply #5 on: June 17, 2021, 04:00:11 PM »
Interesting, I would not have thought it worked like that.  Your expression will give a very large result.  I'll just use ladder logic and two different math boxes.

Thanks.

If you keep the check for MHR2 being non-zero or not too small, you'll get pretty darn close to an accurate result. While adding a very small number to MHR2 only in the equation in the MATH instruction would seem to give a large number, it doesn't matter so much because it is only there to keep from getting the divide by zero error. You will still get the "0" result in your output.

But different MATH instructions works too.