Sunday, October 23, 2005

setting precision in c++

Setting precision in c++

 

 

#include <iostream>

#include <limits>

#include <cmath>

#include <iomanip>

 

template < typename Float >

struct precision {

 

  static unsigned int digits ( unsigned int base ) {

    return( -

            std::log( std::numeric_limits<Float>::epsilon() )

            /

            std::log( base ) );

  }

 

};

 

template < typename Float >

unsigned int sig_digits ( Float const & ) {

  return( precision<Float>::digits(10) ); } 

 

int main ( void ) {

  std::cout << precision<float>::digits( 10 )

            << " "

            << precision<double>::digits( 10 )

            << '\n';

  float x = 2.3345467334234;

  double y = 12.230912093719823691836;

  std::cout << std::setprecision( sig_digits(x) ) << x << '\n';

  std::cout << std::setprecision( sig_digits(y) ) << y << '\n'; }

 

 

 

Pradyut
http://pradyut.tk
http://spaces.msn.com/members/oop-edge/
http://groups-beta.google.com/group/oop_programming
India

 

No comments: