views:

47

answers:

2

I created a calculator class that does basic +,-, %, * and sin, cos, tan, sqrt and other math functions.

I have all the variables of type double, everything is working fine for big numbers, so I can calculate numbers like 1.35E122, but the problem is with extremely small numbers. For example if I do calculation 1/98556321 I get 0 where I would like to get something 1.01464E-8.

Should I rewrite my code so that I only manipulate NSDecimalNumber's and if so, what do I do with sin and cos math functions that accept only double and long double values.

Thank you very much for any insight or help Ladislav

+3  A: 
1/98556321

This division gives you 0 because integer division is performed here - the result is an integer part of division. The following line should give you floating point result:

1/(double)98556321
Vladimir
it still return's 0 even if I do the way you suggested...double nr1 = 1/(double)98556321;NSLog(@"Result = %f", nr1); //Output 0.000000
Ladislav
NSLog displays 6 digits after comma by default but your value is less then that. Try NSLog(@"Result = %.12f", nr1); for example and you'll see that result is not 0.
Vladimir
Oh, thanx, how many decimal places does double and long double support...
Ladislav
+1  A: 

integer/integer is always an integer

So either you convert the upper or the lower number to decimal

(double)1/98556321

or

1/(double)98556321

Which explicitely convert the number to double.

Happy coding....

Suriya
I guess that's why he writes he is using doubles...
Eiko
but the example gave the view that he is dividing integer/integerStill accepting its ma fault... Thanks for explaining Eiko.
Suriya
One problem I have is that I use NSNumberFormatter to format my double values. When I have small numbers like 1E-6 it will convert them to 0.I instantiate NSNumber by initWithDouble method, and then I pass along NSNumber instance to NSNumberFormatter but, still do not get the desired result (only 6 digits)...any thoughts on that?
Ladislav