Boost logo

Boost :

From: Thorsten Ottosen (nesotto_at_[hidden])
Date: 2004-02-29 06:52:09


Dear boosters,

I discovered something that at least was new to me. It's a simple way of
coding floating point
constants s.t.

1. no overhead at all
2. no order dependencies occur
3. the context in which the constant appears decides the precision of the
constants [important in template code]
4. whenever a narrowing or widening conversion is required, explicit action
must be taken by the programmer to determine what he wants
5. all precisions of the constants co-exist, so there is no need for several
headers

Example:

#include "math_constant.hpp"
#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

template< typename T >
void test();

int main()
{
    cout << setprecision( 10 );
    test<float>();
    test<double>();
    test<long double>();
    // cout << pi; // ambiguous
    cout << float( pi ) << " " << double( pi ) << " " << (long double)(
pi ); // ok
    // int i = pi; // ambiguous
    int i = float( pi ); // ok
    cout << sqrt( float( pi ) );
}

template< typename T >
void test()
{
    T two_pi = T(2) * pi;
        two_pi = T(pi) + pi; // note: pi operator X() pi is ambiguous
    T plus = T(1) + pi;
    T minus = pi - T(1);
    T divide = pi / T(2);
    T all = pi + T(3) - T(pi) * pi / T(3); // also ambiguous
    cout << T( pi ) << " ";
}

Any comments are more than welcome. I know there are several proposals for
defining math constants,
but I don't see what the big problems are (so please help me understand them
:-) )

br

Thorsten


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk