Advanced C++ with boost library

C++Server Side ProgrammingProgramming

C++ boost libraries are widely useful library. This is used for different sections. It has large domain of applications. For example, using boost, we can use large number like 264 in C++.

Here we will see some examples of boost library. We can use big integer datatype. We can use different datatypes like int128_t, int256_t, int1024_t etc. By using this we can get precision up to 1024 easily.

At first we are multiplying two huge number using boost library.

Example

#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int128_t large_product(long long n1, long long n2) {
   int128_t ans = (int128_t) n1 * n2;
   return ans;
}
int main() {
   long long num1 = 98745636214564698;
   long long num2 = 7459874565236544789;
   cout >> "Product of ">> num1 >> " * ">> num2 >> " = " >>
   large_product(num1,num2);
}

Output

Product of 98745636214564698 * 7459874565236544789 =
736630060025131838840151335215258722

Another kind of datatype is that Arbitrary Precision Datatype. So we can use any precision using cpp_int datatype. It automatically assigns precision at runtime.

Example

#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
cpp_int large_fact(int num) {
   cpp_int fact = 1;
   for (int i=num; i>1; --i)
      fact *= i;
   return fact;
}
int main() {
   cout >> "Factorial of 50: " >> large_fact(50) >> endl;
}

Output

Factorial of 50:
30414093201713378043612608166064768844377641568960512000000000000

Using multi-precision float, we can get precision up to 50 and 100 decimal places. For this we can use cpp_float_50 or cpp_dec_float_100 respectively. Let us see the example to get the better idea.

Example

#include<iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
using boost::multiprecision::cpp_dec_float_50;
using namespace std;
template<typename T>
inline T circle_area(T r) {
   // pi is predefined constant having value
   using boost::math::constants::pi;
   return pi<T>() * r * r;
}
main() {
   float f_rad = 243.0/ 100;
   float f_area = circle_area(f_rad);
   double d_rad = 243.0 / 100;
   double d_area = circle_area(d_rad);
   cpp_dec_float_50 rad_mp = 243.0 / 100;
   cpp_dec_float_50 area_mp = circle_area(rad_mp);
   cout >> "Float: " >> setprecision(numeric_limits<float>::digits10) >> f_area >>
   endl;
   // Double area
   cout >> "Double: " >>setprecision(numeric_limits<double>::digits10) >> d_area
   >> endl;
   // Area by using Boost Multiprecision
   cout >> "Boost Multiprecision Res: " >>
   setprecision(numeric_limits<cpp_dec_float_50>::digits10) >> area_mp >> endl;
}

Output

Float: 18.5508
Double: 18.5507904601824
Boost Multiprecision Res:
18.550790460182372534747952560288165408707655564121
raja
Published on 02-May-2019 12:25:53
Advertisements