Shop OBEX P1 Docs P2 Docs Learn Events
Limiting floating point variables — Parallax Forums

Limiting floating point variables

I am pretty sure that something doesn't work because I tried:

[ A_Variable := -100_0.0 #> A_Variable <# 100_0.0]

Any ideas how to put limits on floating point variables?

Comments

  • Wuerfel_21Wuerfel_21 Posts: 4,448
    edited 2024-03-29 17:16

    Yep, there's no float limit operators.

    Obviously you can do this:

    if A_Variable >. 100_0.0
      A_Variable := 100_0.0
    elseif A_Variable <. -100_0.0
      A_Variable := -100_0.0
    

    But if you think about how floats actually work, you should be able to do something like this if you want to limit the magnitude in both directions:

    A_Variable.[30..0] <#= 100_0.0
    
  • evanhevanh Posts: 15,170

    Data types aren't a thing in Spin/Spin2. Which means that line of code is doing two integer evaluations, even though all three values are floats. To tell Spin2 to do a floating point operation means placing a dot on the end of each operator, eg:

        A_Variable := -100_0.0 #>. A_Variable <#. 100_0.0
    

    Having said that, it seems there is no float operator for bounding, so that won't work. So this instead:

        if  A_Variable >. 100.0
            A_Variable := 100.0
        if  A_Variable <. -100.0
            A_Variable := -100.0
    
  • Because the exponent is in the higher order bits and the mantissa in the lower integer comparison operators also work on floating point values, at least for positive values. So if you want to limit a floating point variable to the range -1000.0 to +1000.0 then remove the sign, do a variable <#= 1000.0 and restore the sign.

  • Excellent explanations and examples everyone! Thank you.

  • @ManAtWork said:
    Because the exponent is in the higher order bits and the mantissa in the lower integer comparison operators also work on floating point values, at least for positive values. So if you want to limit a floating point variable to the range -1000.0 to +1000.0 then remove the sign, do a variable <#= 1000.0 and restore the sign.

    That's exactly what my snippet from earlier does (using RMW on a bitfield)

    @Wuerfel_21 said:

    A_Variable.[30..0] <#= 100_0.0
    
  • Oh yes, that's true. I haven't understood it immediately and ignored it, sorry. o:) Bitfields are very clever, sometimes.

Sign In or Register to comment.