Thread View: comp.lang.oberon
1 messages
1 total messages
Started by Mike Griebling
Mon, 01 Apr 1996 12:00
Re: Rounding Algorithms?
Author: Mike Griebling
Date: Mon, 01 Apr 1996 12:00
Date: Mon, 01 Apr 1996 12:00
52 lines
2680 bytes
2680 bytes
> Some time ago I wrote some procedures for rounding real numbers: > > PROCEDURE round (x:LONGREAL; n:INTEGER): LONGREAL; > (* Round x to n digits. *) > > PROCEDURE roundp (x:LONGREAL; n:INTEGER): LONGREAL; > (* Round x to n digits behind the decimal point. *) > > PROCEDURE RealToStr (x:LONGREAL; n:INTEGER; VAR s:ARRAY OF CHAR); > (* Convert x to s, rounding to a total of n characters. > n>0: floating point, else exponential. > *) > > I am not so happy with my solutions, because I use logarithms and > exponential functions to generate power-of-10-factors for left- and > right-shifting and ENTIER for truncation. Sometimes arithmetic errors in > those functions give me a result of 9.99 when I want to round 10. > > Does anybody know procedures or algorithms or references about that topic? I wrote some routines which implement a rounding function as follows: real:=real+FIVE*ipower(TEN, exp-sigFigs); where exp is the real number's exponent, sigFigs is the number of significant digits, and ipower raises a floating point number to an integral power using Knuth's algorithm. The number's exponent (exp) is extracted as follows: exp:=0; x:=ABS(x); IF x=ZERO THEN RETURN exp END; (* exception could be raised here *) WHILE x>=TEN DO x:=x/TEN; INC(exp) END; WHILE (x>ZERO) & (x<1.0) DO x:=x*TEN; DEC(exp) END; > Dr. Frank Hrebabetzky Fax: +55 / 48 / 234-1514 I'm not sure if these algorithms will fix your problem but they do not rely on logarithms or exponential functions so they may work out better for you. In general, radix 2 to radix 10 conversions are usually only approximate except when dealing with integral numbers so errors can be expected. Avoid multiplying by the number 0.1 since it is not exactly representable in radix 2 with a finite number of digits. If you need exact decimal numbers, I have some routines which implement these as well (at the expense of not being able to take advantage of floating point hardware). Regards, Michael -------------------------------------------------------------- Michael Griebling, P. Eng. mgriebling@bix.com Computer Inspirations grieblm@trt.allied.com
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads