Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Re: Round to significant figures (C++)

Reply
Thread Tools

Re: Round to significant figures (C++)

 
 
Alf P. Steinbach
Guest
Posts: n/a
 
      05-01-2006
* Phil Cairns:
> I've searched for this one, really I have ...
>
> I have the following C++ function that rounds a double to an integer
> with a given number of significant figures. For instance, rounding 1248
> to 3 signficant figures gives 1250. Rounding 123456789 to 3 significant
> figures gives 123000000.
>
> int setSigFig(double dVal, int nFigs)
> {
> int nSize = (int)log10(dVal) - nFigs + 1;
> if (nSize <= 0)
> {
> return (int)dVal;
> }
> int nFactor = (int)pow(10.0, nSize);
> return ((int)(dVal / nFactor)) * nFactor;
> }
>
> There has to be a more efficient way of doing this. Anyone?


You have limited the function result to the range of int, so I suggest
limiting the argument to the same range...

Here's a starting point (yes, it works):

int firstNDigitsOfPositive( int x, int nDigits )
{
assert( x >= 0 && nDigits > 0 );

IntDigits digits( x );
int const iHighestZero = (digits.n() - 1) - nDigits;

if( iHighestZero >= 0 && digits.at( iHighestZero ) >= 5 )
{
++digits.at( iHighestZero + 1 );
}
for( int i = iHighestZero; i >= 0; --i )
{
digits.at( i ) = 0;
}
return digits.intValue();
}

where IntDigits is a class you have to define; it's probably also a good
idea to define one or more wrappers for this function.


--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Significant figures calculation Harold Python 16 06-28-2011 08:47 PM
Rounding any number (int or float) to 3 significant figures Max Williams Ruby 6 05-16-2009 01:25 PM
Significant Digits (Significant Figures) SMH Javascript 0 01-07-2007 09:52 AM
more than 16 significant figures Jeremy Watts Java 32 07-15-2005 02:21 PM
round up to nearest number and significant figures Steve Java 5 05-17-2004 01:30 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57