Article View: comp.lang.oberon
Article #1247Re: Rounding Algorithms?
From: 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
Technical Details
Message-ID:
<9604011136.AA08852@trt.allied.com>Path:
arc1-ca.pugleaf.net!inf.ethz.ch!oberon-news@inf.ethz.chShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!inf.ethz.ch!oberon-news@inf.ethz.ch From: grieblm@trt.allied.com (Mike Griebling) Newsgroups: comp.lang.oberon Subject: Re: Rounding Algorithms? Date: 1 Apr 1996 14:00:40 +0200 Organization: Dept. Informatik, Swiss Federal Institute of Technology Sender: server@inf.ethz.ch Distribution: world Message-ID: <9604011136.AA08852@trt.allied.com> Reply-To: oberon-news@inf.ethz.ch NNTP-Posting-Host: neptune.inf.ethz.ch Originator: oberon-news@inf.ethz.ch