Limiting floating point variables — Parallax Forums

Limiting floating point variables

Posts: 78

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?

• Posts: 4,696
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
```
• Posts: 15,457

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
```
• Posts: 2,149

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.

• Posts: 78

Excellent explanations and examples everyone! Thank you.

• Posts: 4,696

@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
```
• Posts: 2,149

Oh yes, that's true. I haven't understood it immediately and ignored it, sorry. Bitfields are very clever, sometimes.