MpfrWrapper.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. #ifndef MANDEL_MPFRWRAPPER_H
  2. #define MANDEL_MPFRWRAPPER_H
  3. #include <mpfr.h>
  4. #include <string>
  5. namespace mnd
  6. {
  7. template<unsigned int bits>
  8. class MpfrFloat;
  9. }
  10. template<unsigned int bits>
  11. class MpfrFloat
  12. {
  13. mpfr_t val;
  14. public:
  15. inline MpfrFloat(void)
  16. {
  17. mpfr_init2(val, bits);
  18. }
  19. inline MpfrFloat(const MpfrFloat<bits>& other) : MpfrFloat()
  20. {
  21. mpfr_set(val, other, MPFR_RNDN);
  22. }
  23. inline MpfrFloat(MpfrFloat<bits>&& other)
  24. {
  25. val->_mpfr_d = nullptr;
  26. mpfr_swap(val, other, MPFR_RNDN);
  27. }
  28. inline ~MpfrFloat(void)
  29. {
  30. if (val->_mpfr_d != nullptr)
  31. mpfr_clear(val);
  32. }
  33. inline MpfrFloat<bits>& operator=(const MpfrFloat<bits>& other)
  34. {
  35. mpfr_set(val, other, MPFR_RNDN);
  36. }
  37. inline MpfrFloat<bits>& operator=(MpfrFloat<bits>&& other)
  38. {
  39. mpfr_swap(val, other, MPFR_RNDN);
  40. }
  41. inline MpfrFloat(double v)
  42. {
  43. mpfr_init2(val, bits);
  44. mpfr_set_d(val, v, MPFR_RNDD);
  45. }
  46. inline MpfrFloat(const char* str)
  47. {
  48. mpfr_init2(val, bits);
  49. mpfr_set_str(val, str, 10, MPFR_RNDD);
  50. }
  51. inline MpfrFloat<bits>& operator+=(const MpfrFloat<bits>& other)
  52. {
  53. mpfr_add(val, val, other.val);
  54. }
  55. inline MpfrFloat<bits>& operator-=(const MpfrFloat<bits>& other)
  56. {
  57. mpfr_sub(val, val, other.val);
  58. }
  59. inline MpfrFloat<bits>& operator*=(const MpfrFloat<bits>& other)
  60. {
  61. mpfr_mul(val, val, other.val);
  62. }
  63. inline MpfrFloat<bits>& operator/=(const MpfrFloat<bits>& other)
  64. {
  65. mpfr_div(val, val, other.val);
  66. }
  67. inline MpfrFloat<bits> operator+(const MpfrFloat<bits>& other) const
  68. {
  69. MpfrFloat<bits> result = *this;
  70. result += other;
  71. return result;
  72. }
  73. inline MpfrFloat<bits> operator-(const MpfrFloat<bits>& other) const
  74. {
  75. MpfrFloat<bits> result = *this;
  76. result -= other;
  77. return result;
  78. }
  79. inline MpfrFloat<bits> operator*(const MpfrFloat<bits>& other) const
  80. {
  81. MpfrFloat<bits> result = *this;
  82. result *= other;
  83. return result;
  84. }
  85. inline MpfrFloat<bits> operator/(const MpfrFloat<bits>& other) const
  86. {
  87. MpfrFloat<bits> result = *this;
  88. result /= other;
  89. return result;
  90. }
  91. inline std::string toString(void) const
  92. {
  93. char buf[32 + bits / 2];
  94. int len = mpfr_snprintf(buf, sizeof buf, "%R", val);
  95. if (len > sizeof buf) {
  96. // error
  97. }
  98. return std::string(buf);
  99. }
  100. };
  101. #endif // MANDEL_MPFRWRAPPER_H