Path: news.mathworks.com!not-for-mail
From: "Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid>
Newsgroups: comp.soft-sys.matlab
Subject: Re: decimal precision
Date: Wed, 14 May 2008 00:24:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 55
Message-ID: <g0dbf1$fhj$1@fred.mathworks.com>
References: <g0cmpc$gjg$1@fred.mathworks.com> <g0cpor$h3v$1@fred.mathworks.com>
Reply-To: "Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1210724641 15923 172.30.248.35 (14 May 2008 00:24:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 14 May 2008 00:24:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:468273


"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in 
message <g0cpor$h3v$1@fred.mathworks.com>...
>   You haven't made it clear whether it is only the display of a number or the 
> actual number matlab is using in its computations that is to be altered.  
There 
> is an important difference between the two, though new users often do not 
> distinguish between the two concepts.
> 
>   If you want to display a number to four significant figures, do this:
> 
>  fprintf('The number n equals: %12.4e\n',n)
> 
>   On the other hand, if you want to change the number actually stored in 
> matlab in this manner, do this:
> 
>  m = 4; % Number of significant decimals
>  k = fix(log10(abs(n)))-m+1;
>  n2 = round(10^k*n)/10^k;
>  fprintf('The altered number is: %30.20e\n',n2)
>   = 1.41500000000000003600e+00
> 
>   You will note that if you display the altered number to a sufficient 
accuracy, 
> it is unlikely to be exactly the fraction you requested.  That is because 
> matlab's 'double' format is unable to exactly represent most decimal 
> fractions.
> 
> Roger Stafford
------------
  I was hasty in my earlier response and made three errors.  I should have 
said:

1) To display n to four significant decimals, do:

 fprintf('The number n equals: %10.3e\n',n)

2) To actually alter the number n to the nearest four place decimal, do:

 m = 4; % Number of significant decimals
 k = floor(log10(abs(n)))-m+1;
 n2 = round(n/10^k)*10^k;

  a) The most serious error I made was multiplying n by 10^k instead of 
dividing by it.  That really makes a mess of it!

  b) However, using 'fix' instead of 'floor' is also an error, giving one too few 
significant decimal places for numbers less than 1.

  c) In 1) with %12.4e it would result in 5, not 4, significant decimals being 
displayed.

  Sorry about all that!  Perhaps I stayed up too late last night.

Roger Stafford