I have got an NSString * with for example the following numbers #"182316110006010135232100" and i need to do a calculation with this complete value. I have tried multiple types of number systems on iOS SDK for example Int, Float, etc. But because of the amount of bits it changes the number when i change the StringValue to for example an IntValue.
I need to do the following sum with this complete value: mod(digit, 97);
I have checked with for as far i know the longest type of number in Objective-C Long Long:
long long digit = [(NSString *)shouldBechecksum longLongValue];
And need to do the following calculation:
mod(digit, 97);
Now i get strange results because it does the sum with max version of the number. I need it to do this sum:
mod(182316110006010135232100, 97);
How can i do this calculation correctly?
Thanks!
You can use NSDecimalNumber class for precision up to 38 digits. To obtain the mod, just use this formula with the corresponding NSDecimalNumber methods you'll find explained in the documentation.
Mod = digit - int(digit/97)
This is because NSDecimalNumber can only do the basic operations, you have to obtain the mod as we did in school.
From Apple documentation:
NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.
Fixed Thanks!
NSDecimalNumber *bigDecimal = [NSDecimalNumber decimalNumberWithString:shouldBechecksum];
NSDecimalNumber *divisor = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithDouble:97] decimalValue]];
NSDecimalNumber *quotient = [bigDecimal decimalNumberByDividingBy:divisor withBehavior:[NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:0 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO]];
NSDecimalNumber *subtractAmount = [quotient decimalNumberByMultiplyingBy:divisor];
NSDecimalNumber *remainder = [bigDecimal decimalNumberBySubtracting:subtractAmount];
int checkSum = 98 - [remainder intValue];
I have done a little test with the following code snippet:
NSString *digitStr = #"182316110006010135232100";
long long digit = [(NSString *)digitStr longLongValue];
short checksum = digit % 97;
NSLog(#"%#, %lli, %lli, %i", digitStr, LONG_LONG_MAX, digit, checksum);
The result was:
182316110006010135232100, 9223372036854775807, 9223372036854775807, 78
This means that your value passes the LONG_LONG_MAX value. So, your problem is not feasible this way.
Remark: apparently Objective C puts the value closest to your number in the variabel digit, being LONG_LONG_MAX.
I guess you will have to find some kind of solution for even longer numbers to do what you want to do. Maybe NSDecimalNumber.
Kind regards,
PF
Related
I need to convert the results of calculations performed in a double, but I cannot use decimalNumberByMultiplyingBy or any other NSDecimalNumber function. I've tried to get an accurate result in the following ways:
double calc1 = 23.5 * 45.6 * 52.7; // <-- Correct answer is 56473.32
NSLog(#"calc1 = %.20f", calc1);
-> calc1 = 56473.32000000000698491931
NSDecimalNumber *calcDN = (NSDecimalNumber *)[NSDecimalNumber numberWithDouble:calc1];
NSLog(#"calcDN = %#", [calcDN stringValue]);
-> calcDN = 56473.32000000001024
NSDecimalNumber *testDN = [[[NSDecimalNumber decimalNumberWithString:#"23.5"] decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:#"45.6"]] decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:#"52.7"]];
NSLog(#"testDN = %#", [testDN stringValue]);
-> testDN = 56473.32
I understand that this difference is related to the respective accuracies.
But here's my question: How can I round this number in the most accurate way possible regardless of what the initial value of double may be? And if a more accurate method exists to do the initial calculation, what is that method?
Well, you can either use double to represent the numbers and embrace inaccuracies or use some different number representation, such as NSDecimalNumber. It all depends on what are the expected values and business requirements concerning accuracy.
If it is really crucial not to use arithmetic methods provided by NSDecimalNumber, than the rounding behaviour is best controlled using NSDecimalNumberHandler, which is a concrete implementation of NSDecimalNumberBehaviors protocol. The actual rounding is performed using decimalNumberByRoundingAccordingToBehavior: method.
Here comes the snippet - it's in Swift, but it should be readable:
let behavior = NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundPlain,
scale: 2,
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: false)
let calcDN : NSDecimalNumber = NSDecimalNumber(double: calc1)
.decimalNumberByRoundingAccordingToBehavior(behavior)
calcDN.stringValue // "56473.32"
I do not know of any method of improving the accuracy of the actual computations when using double representation.
I'd recommend rounding the number based on the number of digits in your double so that the NSDecimalNumber is truncated to only show the appropriate number of digits, thus eliminating the digits formed by potential error, ex:
// Get the number of decimal digits in the double
int digits = [self countDigits:calc1];
// Round based on the number of decimal digits in the double
NSDecimalNumberHandler *behavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:digits raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
NSDecimalNumber *calcDN = (NSDecimalNumber *)[NSDecimalNumber numberWithDouble:calc1];
calcDN = [calcDN decimalNumberByRoundingAccordingToBehavior:behavior];
I've adapted the countDigits: method from this answer:
- (int)countDigits:(double)num {
int rv = 0;
const double insignificantDigit = 18; // <-- since you want 18 significant digits
double intpart, fracpart;
fracpart = modf(num, &intpart); // <-- Breaks num into an integral and a fractional part.
// While the fractional part is greater than 0.0000001f,
// multiply it by 10 and count each iteration
while ((fabs(fracpart) > 0.0000001f) && (rv < insignificantDigit)) {
num *= 10;
fracpart = modf(num, &intpart);
rv++;
}
return rv;
}
I have IDs in JSON file and some of them are really big but they fit inside bounds of unsigned long long int.
"id":9223372036854775807,
How to get this large number from JSON using objectForKey:idKey of NSDictionary?
Can I use NSDecimalNumber? Some of this IDs fit into regular integer.
Tricky. Apple's JSON code converts integers above 10^18 to NSDecimalNumber, and smaller integers to plain NSNumber containing a 64 bit integer value. Now you might have hoped that unsignedLongLongValue would give you a 64 bit value, but it doesn't for NSDecimalNumber: The NSDecimalNumber first gets converted to double, and the result to unsigned long long, so you lose precision.
Here's something that you can add as an extension to NSNumber. It's a bit tricky, because if you get a value very close to 2^64, converting it to double might get rounded to 2^64, which cannot be converted to 64 bit. So we need to divide by 10 first to make sure the result isn't too big.
- (uint64_t)unsigned64bitValue
{
if ([self isKindOfClass:[NSDecimalNumber class]])
{
NSDecimalNumber* asDecimal = (NSDecimalNumber *) self;
uint64_t tmp = (uint64_t) (asDecimal.doubleValue / 10.0);
NSDecimalNumber* tmp1 = [[NSDecimalNumber alloc] initWithUnsignedLongLong:tmp];
NSDecimalNumber* tmp2 = [tmp1 decimalNumberByMultiplyingByPowerOf10: 1];
NSDecimalNumber* remainder = [asDecimal decimalNumberBySubtracting:tmp2];
return (tmp * 10) + remainder.unsignedLongLongValue;
}
else
{
return self.unsignedLongLongValue;
}
}
Or process the raw JSON string, look for '"id" = number; '. With often included white space, you can find the number, then over write it with the number quoted. You can put the data into a mutable data object and get a char pointer to it, to overwrite.
[entered using iPhone so a bit terse]
I'm trying to grab a character from a UITextField and find the ascii decimal code value for it. I can save the field value into a char variable, but I'm having trouble obtaining the decimal code value. See below code snippet of the problem.
// grabs letter from text field
char dechar = [self.decInput.text characterAtIndex:0]; //trying to input a capital A (for example)
NSLog(#"dechar: %c",dechar); // verifies that dechar holds my intended letter
// below line is where i need help
int dec = sizeof(dechar);
NSLog(#"dec: %d",dec); //this returns a value of 1
// want to pass my char dechar into below 'A' since this returns the proper ASCII decimal code of 65
int decimalCode = 'A';
NSLog(#"value: %d",decimalCode); // this shows 65 as it should
I know going the other way I can just use...
int dec = [self.decInput.text floatValue];
char letter = dec;
NSLog(#"ch = %c",letter); //this returns the correct ASCII letter
any ideas?
Why are you using the sizeof operator?
Simply do:
int dec = dechar;
This will give you 65 for dec assuming that dechar is A.
BTW - you really should change dechar to unichar, not char.
iOS uses unicode, not ASCII. Unicode characters are usually 16 bits, not 8 bits.
Look at using the NSString method characterAtIndex, which returns a unichar. A unichar is a 16 bit integer rather than an 8 bit value, so it can represent a lot more characters.
If you want to get ASCII values from an NSString, you should first convert it to ASCII using the NSString method dataUsingEncoding: NSASCIIStringEncoding, then iterate through the bytes in the date you get back.
Note that ASCII can only represent a tiny fraction of unicode characters though.
I'm having some trouble calculating the result of an 8-digit number to the power of a 3-digit number programmatically in Objective-C.
Take these numbers, for instance: 16468920^258, which should result in a number that is 1862 digits in length.
I naïvely tried:
unsigned long long result = 1;
for (int i = 0; i < 258; i++)
result *= 16468920;
…but result outputs 0.
Then I tried:
long double result = powl(16468920, 258);
…but result outputs inf.
After finding out about NSDecimal, I tried this:
NSDecimal result;
NSDecimal number = [[NSDecimalNumber decimalNumberWithString:#"16468920"] decimalValue];
NSDecimalPower(&result, &number, 258, NSRoundPlain);
…but result outputs NaN, so I tried:
NSDecimalNumber *number = [[NSDecimalNumber alloc] initWithInt:16468920];
NSDecimalNumber *result = [number decimalNumberByRaisingToPower:258];
…but this code raises an NSDecimalNumberOverflowException.
Any pointers as to which direction I should be going?
Since Objective-C is a superset of C, you can use a C library such a BN:
int BN_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BN_CTX *ctx);
BN_exp() raises a to the p-th power and places the result in r ("r=a^p"). This
function is faster than repeated applications of BN_mul().
See, for example, here for how to get openssl into iOS.
You get that issue because your result still bigger that NSDecimalNumber could store.
I recommend you to could use JKBigInteger instead, it is a Objective-C wrapper around LibTomMath C library. And really easy to use and understand.
Hope this could help.
Why does the %g format for strings only handle six numbers in a float and after that it turns into scientific notation? Is there any other way of displaying a float with something similar to the %g format but allows more than six numbers?
EDIT: I have figured out %g with precision i.e turning %g into %.Xg where x is the specified number of significant digits. But it doesnt help me in this situation:
-(IBAction)numberPressed:(id)sender {
if (decimalChecker == 1) {
currentDecimal = currentDecimal*10+ (float)[sender tag];
decimaledNumberString = [[NSString alloc] initWithFormat:#"%.17g.%.17g", currentNumber, currentDecimal];
calculatorScreen.text = decimaledNumberString;
currentDecimaledNumber = [decimaledNumberString floatValue];
NSLog(#"regular");
} else {
currentNumber = currentNumber*10+ (float)[sender tag];
calculatorScreen.text = [[NSString alloc] initWithFormat:#"%.17g", currentNumber];
NSLog(#"regular");
}
}
If I press "5" eight times instead of 55555555, I get 55551782 or something similar. How can I fix it to where I get the desired eight fives instead of the crazy number?
Insert a period and a numeral to specify the maximum number of significant digits you would like displayed, such as %.17g for 17 significant digits. As you discovered, the default is six.
According to http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Strings/Articles/FormatStrings.html#//apple_ref/doc/uid/20000943, iOS string formatting uses the same placeholders as C's printf(), which specifies g/G as representing FP values with exponential notation for very large/small values while f only uses non-exponential representation.
http://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders