-4

I'm -kind of- a beginner to C.

I made several searches but I haven't seen this question asked. When I try to calculate very big numbers (let's say... Adding 45235432412321312 to 5495034095872309238) my calculator gives answers which are not true. (The answer of my calculator was -2 for the numbers I've given in the previous sentence).

But both Linux's and Windows's own calculators calculate these numbers precisely.

What causes my calculator written in C/C++ to give these wrong answers with big numbers? What can I do to calculate these?

3 Answers3

3

Digital data is represented as binary information. So, for an 8-bit integer you would have: 0=00000000, 1=00000001, 2=00000010, 3=00000011, etc. As you can imagine, the larger the numbers grow, the more storage is required to represent this information in binary form. What happens with your calculator is called overflow, where the resulting number is simply too large to represent in binary form (there are not enough bits to hold the information).

Now as to why you get accurate results in your computer, it depends on how their software is implemented. Possible explanations are that they either use higher precision arithmetic (they dedicate more bits) the use multiple precision arithmetic, or perform floating point calculations internally. My money would be on multiple precision arithmetic though.

Nikos Kazazakis
  • 792
  • 5
  • 19
1

Simply put, the built-in numeric data types that you're using within C and C++, such as float, int, etc., are limited due to them being represented with a finite and fixed amount of bits, such as 32, 64, etc. bits. You can't "stuff" more information into 32 bits than you can, that's the theory of information (read up). Now, when you add two "very big" numbers, due to the machine representation, a so-called "overflow" occurs (read up), which means that a bit sequence is being created as a result of the operation that represents a "meaningless" number; and if the data type is signed, a negative number is likely to appear (again, due to the internal representation).

Now your calculators use so-called "big numbers arithmetic", or "long numbers arithmetic", implemented in the corresponding libraries. With this approach, the number is represented as an array of numbers, and is thus virtually unlimited (of course, there are limits to the length of an array too, but the range that you can represent this way is a lot wider than that of the built-in types.)

To sum up, read on:

  • theory of information
  • binary number system and conversions decimal <-> binary
  • binary arithmetics with signed numbers
  • big number arithmetics
iksemyonov
  • 4,106
  • 1
  • 22
  • 42
1

Short answer (and I'm not sure why you didn't find it, because it's been asked many, many times): you want a multiple-precision arithmetic library, such as GMP.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103