Home > database >  How to perform exponentiation using boost multiprecision and boost math?
How to perform exponentiation using boost multiprecision and boost math?

Time:08-22

I am running a biased Monte Carlo simulation, and I need to process the energies being reported. I essentially have to compute exp(-beta*energy), where energy is a negative number and beta can be around 100. If energy = 90, std::exp starts outputting inf. This is a test run:

#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/special_functions/expm1.hpp>
#include <iostream>
#include <cmath>

int main()
{
   // using namespace boost::multiprecision;

    double u = std::exp (900.0);

   boost::multiprecision::cpp_dec_float_50 v = 2.71;

   // loop for e^900
   for(unsigned i = 1; i < 901;   i){
      v *= 2.71;
   }
   
   boost::multiprecision::cpp_dec_float_50 x = boost::math::expm1 (900.0);

   std::cout << "u = " << u << std::endl; 
   std::cout << "v = " << v << std::endl; 
   std::cout << "x = " << x << std::endl;  

   return 0;
}

Results:

u = inf
v = 1.27447e 390
x = inf

My question is, how do i perform this exponentiation, and get the answer like in v?

CodePudding user response:

Just use exp! Live On Compiler Explorer

boost::multiprecision::cpp_dec_float_50 x = 900.0;
std::cout << "v = " << exp(x) << std::endl; 

Prints

v = 7.32881e 390

The difference between exp(900.0) and exp(x) is that 900.0 is of type double and x is cpp_dec_float_50.

ADL finds the correct overload for exp in the associated namespace.

  • Related