J

#### JimU

For some utility streams that may have totalizers that run without resetting for a year or more, the sum can get very large while the increment is small. To avoid problems with machine accuracy (for what value of j does your machine give you 1.0 + 1.0E-j = 1.0?), I split the total into an integer (SUMi) and floating point (SUMf) part as in the following pseudocode. Here, Trigger is an integer.

SUMf = raw*scale*dt + SUMf
IF SUMf > FLOAT(Trigger) THEN
SUMi = SUMi + Trigger
SUMf = SUMf – FLOAT(Trigger)
ENDIF

For display or recording, the sum is SUMi + SUMf. Sometimes it’s necessary/convenient to maintain SUMi in accumulators. Other approaches are possible… the idea here is to avoid roundoff error associated with adding large and small floats a billion times over the course of a year, especially towards the end of the year.

J

#### Jiri Baum

Actually, the first thing to do is check how many digits you actually need, and see if you can use a double or something. If you can't, at least you have a good basis for deciding how to replace it-range and accuracy.

> SUMf = raw*scale*dt + SUMf
> IF SUMf > FLOAT(Trigger) THEN
> SUMi = SUMi + Trigger
> SUMf = SUMf - FLOAT(Trigger)
> ENDIF

> For display or recording, the sum is SUMi + SUMf.

Of course, you have to be careful to avoid overflowing the integer, too.
You'd end up repeating the trick several times to give you as much range as
you need (see above analysis).

f = f + raw*scale*dt
for i = 0 .. n-1 do
if f>trigger then
f[i+1] = f[i+1] + 1
f = f - trigger
endif
endfor

(This code puts everything in floats for simplicity.)

> Other approaches are possible--- the idea here is to avoid roundoff error
> associated with adding large and small floats a billion times over the
> course of a year, especially towards the end of the year.

Probably the best approach would be to eliminate the floats altogether and do everything in fixed point (or scaled integers). That way you'll know exactly what accuracy you have, and it'll likely be faster to boot.

Jiri
--
Jiri Baum <[email protected]> http://www.csse.monash.edu.au/~jirib
MAT LinuxPLC project --- http://mat.sf.net --- Machine Automation Tools