I'm doing my calculator and it's helping me until now. But in some cases, the rounding is not working fine.
Ex: when the result should be 4, the printout becomes 3.9999999 .
I know to avoid this problem is to calculate by the value in memory, instead of it's real value.
My questions:
1. How to access the memory value (read and store a value)?
2. How to do the calculation? (addition, subtract, divide, multiply, power)
3. How to display the result?
Edit: Currently, I'm using double for my value container.
I don't understand what you believe is the solution. The problem you are encountering is floating point roundoff error. Your best solution, if possible, is to perform the math using integers.
Actually, I want to modify my code to work that way. Currently, I'm just using normal operation such as 2 + 3 . I'd want to access the binary value of 2 and 3 so I can operate it as binary (maybe this should be the keyword) before returning as real number.
I may convert these integers to binary, but the exponential numbers are quite difficult...
By the way, how do you calculate double in integer representation (beside of using fraction) ?
If you want a really simple solution, and don't mind limited accuracy (but hey, when will you not have limited accuracy, or infinite significant figures anyway?), you can tell your printing command to round to the nearest so many digits.
If the 2.0 is 0000 0010 (is it?) in computer memory, how can I get the value so I can compute it?
It's the binary representation of the integer 2; the IEEE 756 double value is stored differently; see the above link.
And about that accuracy: use a multi-precision rational type. Speed won't be an issue for a calculator. If you require exact root calculations, there is a data type LEDA::real which can handle that (it's not free, though. And if you want to write it yourself, you will require some solid mathematical knowledge about algebraic numbers and their construction (there is a beautiful constructive proof that the algebraic numbers are a field, using the Sylvester resultant, which would help you))
Hmm... I remember that it require pointers to access the bits.
For the calculation, I may be able to solve it -somehow-. But now, I just need to work on obtaining the bits.
I'll continue my work then and I'll come back after some stressess...
If you guys have any suggestion, please post it.
The way I usually access a single bit is bitwise logic or shifting. Given the standard for floating point numbers, you would need to know the significance of the bit(s) you are testing, i.e. sign exponent mantissa.
Using integers, it's a bit more obvious. If (a & b) is not zero, then the numbers both have at least one bit in common that is 1.
1 2 3
int a,b;
b = 2 * 2;
printf("What is a's 3rd bit? %s", (a & b)? "It's a 1\n" : "It's a 0\n");