5

SP4CEBAR 2022-08-03 13:37 (Edited)

Here are two subprograms I use all the time: fullmod, and varbound

- fullmod is like modulo, but it keeps the pattern going in the negative numbers, AND could do the same thing (A MOD 4 and A AND 3 are similar) but that only works for powers of two, for other numbers I use fullmod, to use it: you could replace

"N = N MOD B" with "CALL FULLMOD(N,B)" - varbound keeps a value (V) between two boundaries (L,H), when it's greater than the maximum it is clipped to the maximum value, when it's smaller than the minimum, it is clipped to the minimum value

```
SUB FULLMOD(N,B0)
IF B0=0 THEN B=1 ELSE B=B0
N=-((N MOD B)*(N>=0)+((B-1)+((N+1) MOD B))*(N<0))
END SUB
```

```
SUB VARBOUND(V,L,H)
IF V<L THEN
V=L
ELSE IF V>H THEN
V=H
END IF
END SUB
```

McPepic 2022-08-03 19:06

Alternatively, you could do:

SUB _MOD(A,B)

ADD A,-INT(A/B)*B

END SUB

SUB CLAMP(A,L,H)

A=MAX(L,MIN(A,H))

END SUB

Just thought I would provide an alternative. :)

SP4CEBAR 2022-08-03 19:22

wow, a oneliner for every function, I'm impressed! :D

I didn't realize how over-engineered my subprograms were until I saw how simple they could be, wow

McPepic 2022-08-03 19:27

That's the fun part about programming. There's always more than one way to solve a problem! (I also learned the modulo trick on Stack Overflow)

Log in to reply.