What class to use for money representation?

Never use a floating point number to represent money. Floating numbers do not represent numbers in decimal notation accurately. You would end with a nightmare of compound rounding errors, and unable to reliably convert between currencies. See Martin Fowler’s short essay on the subject. If you decide to write your own class, I recommend basing … Read more

Hash an arbitrary precision value (boost::multiprecision::cpp_int)

You can (ab)use the serialization support: Support for serialization comes in two forms: Classes number, debug_adaptor, logged_adaptor and rational_adaptor have “pass through” serialization support which requires the underlying backend to be serializable. Backends cpp_int, cpp_bin_float, cpp_dec_float and float128 have full support for Boost.Serialization. So, let me cobble something together that works with boost and std … Read more

How to add 2 arbitrarily sized integers in C++?

Here’s an example showing how to use the OpenSSL bignum implementation for arbitrary-precision arithmetic. My example does 264 + 265. I’m using Linux. #include <cstdio> #include <openssl/crypto.h> #include <openssl/bn.h> int main(int argc, char *argv[]) { static const char num1[] = “18446744073709551616”; static const char num2[] = “36893488147419103232”; BIGNUM *bn1 = NULL; BIGNUM *bn2 = NULL; … Read more

numpy arbitrary precision linear algebra

SymPy can calculate arbitrary precision: from sympy import exp, N, S from sympy.matrices import Matrix data = [[S(“-800.21”),S(“-600.00”)],[S(“-600.00”),S(“-1000.48”)]] m = Matrix(data) ex = m.applyfunc(exp).applyfunc(lambda x:N(x, 100)) vecs = ex.eigenvects() print vecs[0][0] # eigen value print vecs[1][0] # eigen value print vecs[0][2] # eigen vect print vecs[1][2] # eigen vect output: -2.650396553004310816338679447269582701529092549943247237903254759946483528035516341807463648841185335e-261 2.650396553004310816338679447269582701529092549943247237903254759946483528035516341807466621962539464e-261 [[-0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999994391176386872] [ 1]] … Read more

How to generate random 64-bit value as decimal string in PHP

This was a really interesting problem (how to create the decimal representation of an arbitrary-length random number in PHP, using no optional extensions). Here’s the solution: Step 1: arbitrary-length random number // Counts how many bits are needed to represent $value function count_bits($value) { for($count = 0; $value != 0; $value >>= 1) { ++$count; … Read more

Can long integer routines benefit from SSE?

In the past, the answer to this question was a solid, “no”. But as of 2017, the situation is changing. But before I continue, time for some background terminology: Full Word Arithmetic Partial Word Arithmetic Full-Word Arithmetic: This is the standard representation where the number is stored in base 232 or 264 using an array … Read more