Hi, I am trying to create an Rcpp package that involves arbitrary precise calculations. The function to calculate e^x below with 100 digits precision works well with integers, but for decimals, since the input is a double, the result differs a lot from the arbitrary precise result I got on Wolfram.
I understand the results are different since 0.1 cannot be represented precisely in binary with limited bits. It is possible to enter 1 then 10 and get the multiprecision division of these two integers to attain a more precise 0.1 in C++, but this method won't work on a large scale. Thus, I am looking for a general solution to get more precise inputs? The dummy example is as follows: library(Rcpp) sourceCpp(code = ' #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/special_functions/expm1.hpp> // [[Rcpp::depends(BH)]] // [[Rcpp::export]] std::string calculateExp100(double x) { boost::multiprecision::cpp_dec_float_100 bx = x; boost::multiprecision::cpp_dec_float_100 expx = exp(bx); return expx.str(50); } ') [1] represents the R output and [W] for Wolfram results calculateExp100(1) # Agrees with Wolfram answer all the way to the last digit [1] "2.7182818284590452353602874713526624977572470937" [W] 2.7182818284590452353602874713526624977572470936999595749669676277... calculateExp100(0.1) # Differs pretty significantly from Wolfram's answer [1] "1.1051709180756476309466388234587796577416634163742" [W] 1.1051709180756476248117078264902466682245471947375187187928632894... I am currently trying to get precise inputs by taking strings instead of numbers then writing a function to decompose the string into a rational with the denominator in the form of 10^(-n) where n is the number of decimal places. I am not sure if this is the only way or if there is a better method out there that I do not know of, so if you can think of a general way to get precise inputs from users, it will be greatly appreciated! Thank you! Best, Khue Tran -- *Khue B. Tran (she/her/hers)* tr...@kenyon.edu | +1 (220) - 203 - 9306 | LinkedIn <https://www.linkedin.com/in/tranbaokhue/> Mathematics and Music Double Major, Kenyon College '25 [[alternative HTML version deleted]] ______________________________________________ R-package-devel@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-package-devel