Obtaining float from division between NSIntegers - objective-c

I have two NSInteger variables called "domande" and "corrette". I have to execute this operation with them: corrette*10/domande. I want the result to be a float variable, so I declared a "voto" variable as so: "float voto = corrette*10/domande;" . When I output the value of "voto" with NSLog I get an approximated value of the result followed by ".000000".
Here's the code:
NSInteger domande = [numDomande integerValue];
NSInteger corrette = [numRisposteCorrette integerValue];
float voto = corrette*10/domande;
NSLog(#"float value is: %f", voto);
When I assign to "domande" a value of 7, and to "corrette" a value of 4: voto=5.000000
Instead it should be voto=5.71...
How can I have the division return not an integer type converted to float, but directly a float type?

Simplest way is to do:
float voto = 10.0f * corrette / domande;
By making the first argument a float, you guarantee that the others will be promoted as well and that intermediate and final results will not suffer truncation.
You could achieve a similar result by casting corrette to a float but I tend to prefer simplicity where possible.

Rather than converting integers to floats, you could just get floats in the first place:
CGFloat domandeFloat = [numDomande floatValue];
CGFloat corretteFloat = [numRisposteCorrette floatValue];
CGFloat voto = (corretteFloat / domandeFloat) * 10.0f
NSLog(#"float value is: %f", voto);

NSInteger does not have a method called floatValue. NSInteger is just an int. Instead, the solution would be:
CGFloat domandeFloat = [[NSNumber numberWithInt: numDomande] floatValue];
CGFloat domandeFloat = [[NSNumber numberWithInt: numRisposteCorrette] floatValue];
CGFloat voto = (corretteFloat / domandeFloat) * 10.0f;

Try to convert the NSIntegers to a float type first:
float voto = (float)corrette*10/(float)domande;

you can cast "10" from int to float by writing it as "10.0"
float voto = corrette*10.0/domande;
or
float voto = ((float)corrette*10) / (float)domande;
Operation "/" is returning type of it operands - 5/4 will return int result 1 because 5 and 4 are int, and 5.0/4.0 will return 1.25, because 5.0 and 4.0 are interpreted as float values. So you should manually cast type of input variables corrette and domande to float

Related

How to use decimal variable

I am using a For loop to cycle through variables in an array that contain percentages. For each value I run through an equation to give me an average of all the percentages. The only problem is that I am unsure how to change the variable types to accommodate decimals whilst also work in with my equation.
// Calculate average of all percentages for specific exercise
long totalNumber = 0;
int temp;
long numberOfObjects = [iterationArray count];
for (NSArray *object in iterationArray) {
temp = [(NSNumber *)[object objectAtIndex:4] intValue]/100;
totalNumber = totalNumber + temp;
}
exercisePercentage = (totalNumber/numberOfObjects)*100;
return exercisePercentage;
I know that temp is the variable that needs to be a decimal. I was considering using an NSDecimalNumber but didn't know how to fit in with the rest of the code to return a long value.
I've tried with making temp a double or float but both return 0 on the line temp = [(NSNumber *)[object objectAtIndex:4] intValue]/100; despite the fact that [(NSNumber *)[object objectAtIndex:4] intValue] is 80.
Division of int with int always returns int, so you need to convert one value into float or double, something like this:
// Calculate average of all percentages for specific exercise
double totalNumber = 0.0;
double temp;
long numberOfObjects = [iterationArray count];
for (NSArray *object in iterationArray) {
temp = [(NSNumber *)[object objectAtIndex:4] intValue]/100.0;
totalNumber = totalNumber + temp;
}
exercisePercentage = (totalNumber/numberOfObjects)*100.0;
return exercisePercentage;
See it's 100.0, now it should work.
Please change the type of temp form int to float or double.
double temp;
float temp;

Objc: convert unsigned long to float [duplicate]

It might be a simple solution but I can not fix it.
I am dividing 2 integers :
finishedGameFinalScore = [score integerValue];
CGFloat interval = 2/finishedGameFinalScore;
NSLog(#"interval = %f",interval);
The log returns 0.000000
Is there a limit for decimal places? I need to preserve the decimal result.
Thanks
Shani
The reason your code doesn't work is that you're dividing an integer by another integer and then casting the result to a float.
So you have 2 (an integer) and some other number (also an integer). Then you divide 2 by this number - which is probably greater than 2. Let's say it's 3.
Integer sees 2/3 and he's like "0.66666667? Pshh, no one ever needs anything after the decimal point anyway". So he truncates it. You just have 0.
Then Integer gives the number to Mr. float and Mr float is super happy to get a number! He's all like "yay, a 0! I'm going to add ALL OF THE SIGNIFICANT DIGITS". And that's how you end up with 0.0000000.
So yeah, just cast to a float first. Or even a double!
#Dustin said u will need to typecast your divider value to float as it goes in float it shows integer value
CASE 1: Typecast
NSString *score = #"3";
int interval = [str intValue];
CGFloat interval = (2/(float)interval);
NSLog(#"interval = %.2f",interval);
CASE 2: No need for typecast
NSString *score = #"3";
float interval = [str floatValue];
CGFloat interval = (2/interval);
NSLog(#"interval = %.2f",interval);
Just add the f-hint to the number 2. in this case that will do the trick.
CGFloat interval = 2.0f/finishedGameFinalScore;
all the above/below answers are correct and fully explain why this work.
just devide long value from 1.0 and assigned to float variable.
unsigned long l1 = 65536;
unsigned long l2 = 256;
float f = (l1/1.0)/(l2/1.0);
NSLog(#"%f",f);

speed up this Standard Deviation method

I have this method to calculate the standard deviation of an array of NSNumber integers, given a mean. The calculation uses NSDecimals to retain the highest resolution. This is currently demanding many cpu cycles, any help to speed it up while retaining the resolution required is appreciated! Thank you.
-(NSDecimal)standardDeviationOf:(NSMutableArray *)array withMean:(NSDecimal)mean {
if (![array count]) return CPTDecimalFromInt(0);
NSDecimal sumOfSquaredDifferences = CPTDecimalFromInt(0);
for (NSNumber *number in array) {
NSDecimal valueOfNumber = CPTDecimalFromInt([number intValue]);
NSDecimal difference = CPTDecimalSubtract(valueOfNumber, mean);
sumOfSquaredDifferences = CPTDecimalAdd(sumOfSquaredDifferences, CPTDecimalMultiply(difference, difference));
}
return CPTDecimalFromDouble(
sqrt(
CPTDecimalDoubleValue(sumOfSquaredDifferences) / [[NSNumber numberWithInt:[array count]] doubleValue]
)
);
}
An NSDecimal has 38 digits of precision, whereas double has roughly 16 digits of precision. But at the end of your loop, when you convert sumOfSquaredDifferences to double for the sqrt function, all the extra precision you had in the NSDecimal is "lost". You might as well perform the arithmetic of your inner loop using double, which should be much faster than NSDecimal:
double sumOfSquaredDifferences = 0;
double valueOfMean = [mean doubleValue];
for (NSNumber *number in array) {
double valueOfNumber = [number intValue];
double difference = valueOfNumber - valueOfMean;
sumOfSquaredDifferences += difference * difference;
}
return CPTDecimalFromDouble(sqrt(sumOfSquaredDifferences /
double([array count])));

NSNumber decimal to C primitive value?

I want to convert a decimal NSNumber to an int or other form which I can do math with. Here's the annotated code for my project:
NSNumber *Left = [left valueForOutputKey:#"Y"];
This line gets a Quartz Composer Outlet, usually with a value around 0.512.
Basically, I want to multiply this by 10, and then do some operations like greater than and less than to see which range it is in.
Since it looks like you're dealing with a fractional component, you want to convert it to a float or a double to perform your operations, depending on how big you expect that value to be. A float should be fine unless you're dealing with ridiculously large or precise numbers. Here's how it would look, for example:
float lValue = [[left valueForOutputKey:#"Y"] floatValue];
lValue *= 10;
if (lValue < 10) {
// do whatever
}
else if (lValue > 50) {
// do whatever
}
Then to store the value back in your outlet or whatever, you pack it back into a NSNumber:
NSNumber *newValue = [NSNumber numberWithFloat:lValue];
[left setValue:newValue forKey:#"Y"];
You may have to convert newValue into a string to display it in a control, just use [newValue stringValue] to do that.
Use one of the methods of NSNumber:
int leftInt = [Left intValue];
float leftFloat = [Left floatValue];
double leftDouble = [Left doubleValue];

How to round an float value and convert it into NSInteger value in the iPhone SDK?

I need to round a float value and convert it into an NSInteger value.
For example:
float f = 90.909088;
I want the result to be 91. How to get rid of this?
A quick round and cast will work for negative values as well as positives:
NSInteger intValue = (NSInteger) roundf(f);
One of the following C math functions might work for you:
double ceil(double)
double floor(double)
double nearbyint(double)
double rint(double)
double round(double)
long int lrint(double)
long int lround(double)
long long int llrint(double)
long long int llround(double)
double trunc(double)
To get more documentation, open a terminal session and type (for example)
man lround
I pick lround as an example because I think that is the one you want.
Do
f = floor(f + 0.5)
before the integer conversion.
Try:
float f = 90.909088;
NSNumber *myNumber = [NSNumber numberWithDouble:(f+0.5)];
NSInteger myInt = [myNumber intValue];