News:

  • October 13, 2025, 07:20:44 AM

Login with username, password and session length

Author Topic: "Clamping" in a MATH Instruction  (Read 2311 times)

Bolt

  • Hero Member
  • *****
  • Posts: 591
"Clamping" in a MATH Instruction
« on: December 29, 2020, 12:42:04 PM »
I have a MATH instruction referencing many other variables calculating to an Unsigned Word.  V0 = -R0 + (!C0 * D0) + (C0 * R1) + R2 + R3 Due to the many inputs, sometimes the calculation goes slightly negative, such as -5.23, so the value returns as ~ 65540.  Is there a clean way to prevent this from happening, returning a value of 0, without having to wrap the whole expression in an IF, V0 = IF(-R0 + (!C0 * D0) + (C0 * R1) + R2 + R3 < 0, -R0 + (!C0 * D0) + (C0 * R1) + R2 + R3)?  I'm trying to keep my logic simple and avoid helper elements and/or additional instructions.

franji1

  • Bit Weenie
  • Host Moderator
  • Hero Member
  • *****
  • Posts: 3761
    • Host Engineering
Re: "Clamping" in a MATH Instruction
« Reply #1 on: December 29, 2020, 02:54:19 PM »
MAX(base-expression, 0.0)

Even though the DESTINATION is UNSIGNED, the calculation is REAL (since you are using R's).  Hence, MAX(anything, 0.0) will return 0.0 if anything is negative, otherwise it returns anything.

Bolt

  • Hero Member
  • *****
  • Posts: 591
Re: "Clamping" in a MATH Instruction
« Reply #2 on: December 29, 2020, 08:13:16 PM »
Thanks, that makes for a much cleaner instruction.

Bolt

  • Hero Member
  • *****
  • Posts: 591
Re: "Clamping" in a MATH Instruction
« Reply #3 on: December 29, 2020, 08:24:04 PM »
What are the chances y'all could make a "MathSim", where we could test drive MATH instructions in a program/utility without having to write a few rungs with trigger coils and dummy values to the DmSim or PLC to test drive a complicated math equation?

Mike Nash

  • Hero Member
  • *****
  • Posts: 645
Re: "Clamping" in a MATH Instruction
« Reply #4 on: December 29, 2020, 10:53:19 PM »
... and

MIN(MAX(base-expression, min-clamp),max-clamp)

clamps between two values.

That is sweet.