www.piclist.com/techref/index.htm?key=brain+burp+rounding

William Chops Westfield <STOPspambillwspamBeGoneKILLspamcisco.com> wrote:

> Is there a simple algorithm for doing the odd/even rounding

> (equivilent to N+0.5 and truncate?)

Bill:

There's a simple implementation in PIC assembly:

; Enter with integer in REG, fraction in the Carry flag.

BNC DONE ;If the carry's clear, no rounding

;is required, so jump.

BTFSS REG,0 ;If the integer is odd, skip ahead.

INCF REG ;Otherwise, round up (i.e., round

;to odd).

DONE:

This implementation uses "round to odd" rather than "round to even"

in order to make the rounding of multi-byte integers easier; with

this method, only the least-significant byte is ever changed.

This introduces a tiny bit of bias, however, since only ONE value

(0.0) rounds to 0 while THREE values (254.5, 255.0, and 255.5) round

to 255.

If it were important for numbers close to 0 to round down to 0, you

could reverse things so that the bias was toward 0 rather than 255...

But then you'd non-intuitively be rounding 1.0 to 0.

-Andy

=== Andrew Warren --- @spam@aiw@spam@cypress.com

=== IPD Systems Engineering, CYSD

=== Cypress Semiconductor Corporation

===

=== Opinions expressed above do not

=== necessarily represent those of

=== Cypress Semiconductor Corporation

--

http://www.piclist.com hint: PICList Posts must start with ONE topic:

[PIC]:,[SX]:,[AVR]: ->uP ONLY! [EE]:,[OT]: ->Other [BUY]:,[AD]: ->Ads

In reply to: <CMM.0.90.4.991428725.billw@cypher>

See also: www.piclist.com/techref/index.htm?key=brain+burp+rounding