Return zero or positive number? - iphone

I was initially thinking that the code below would return 0, my question, is there a function that I can use to only receive zero/positive results here?
NSUInteger pruneSize = 5 - 20; // Returns: -15
Currently I am just checking the result myself, but was wondering if I was missing something simpler.
NSUInteger pruneSize = 5 - 20;
if(pruneSize >= 0) {
// Do zero/positive Stuff ...
}

pruneSize >= 0 is always true as pruneSize is unsigned. You should get a warning here. You need to change the type to NSInteger, that is the signed integer. If you want to clip the lower value to zero for a signed int then you can do this:
NSInteger pruneSize = 5 - 20; // signed int
pruneSize = pruneSize < 0 ? 0 : pruneSize;

You can use abs(pruneSize) which will return you positive or zero number in any case.
EDIT:
NSUInteger pruneSize = 5-20;
if(pruneSize < 0)
{
pruneSize = 0;
}
NSLog(#"%d",pruneSize);
Hope this helps you.

If you want your function to return always zero if your result is in negative(less than 0) then return zero or else return result
int n=0;
if(result > 0){ //positive
n = result
else
n = 0
return n
or use the abs method

Related

Is there any way to convert from double to int in dart

I want to solve leetcode 172nd question using dart. Take the factorial of a given number and find how many zeros there are at the end.
I done until now
void main() {
print(factorial(5));
}
factorial(int input) {
int factorial = 1;
var answer = 0;
for (int i = 1; i <= input; i++) {
factorial *= i;
}
while (factorial > 10 && factorial.toString().split('').last == "0") {
factorial = (factorial / 10)
answer++;
}
return answer;
}
but when i divide factorial by 10 it not allowed. and if assing at the begining like
double factorial=1;
this time the number is 120.0 and then zero is more. Can anyone help on this, thanks
You can use method for double to int;
double a = 8.5;
print(a.toInt()) // 8
Answer:
while (factorial > 10 && factorial.toString().split('').last == "0") {
factorial = (factorial / 10).toInt(); // Add toInt()
answer++;
}
To convert a double to int, just use:
double x = 1.256;
print(x.toInt()); //this will print 1
I am not sure what you are asking in this question other than this.
Check the accepted answer to this Question: How to do Integer division in Dart?
Integer division in Dart has its own operator: ~/ as in
print(16 ~/ 3);

Calculate IRR (Internal Rate Return) and NPV programmatically in Objective-C

I am developing a financial app and require IRR (in-built functionality of Excel) calculation and found such great tutorials in C here and such answer in C# here.
I implemented code of the C language above, but it gives a perfect result when IRR is in positive. It is not returning a negative value when it should be. Whereas in Excel =IRR(values,guessrate) returns negative IRR as well for some values.
I have referred to code in above C# link too, and it seems that it follows good procedures and returns errors and also hope that it returns negative IRR too, the same as Excel. But I am not familiar with C#, so I am not able to implement the same code in Objective-C or C.
I am writing C code from the above link which I have implemented for helping you guys.
#define LOW_RATE 0.01
#define HIGH_RATE 0.5
#define MAX_ITERATION 1000
#define PRECISION_REQ 0.00000001
double computeIRR(double cf[], int numOfFlows)
{
int i = 0, j = 0;
double m = 0.0;
double old = 0.00;
double new = 0.00;
double oldguessRate = LOW_RATE;
double newguessRate = LOW_RATE;
double guessRate = LOW_RATE;
double lowGuessRate = LOW_RATE;
double highGuessRate = HIGH_RATE;
double npv = 0.0;
double denom = 0.0;
for (i=0; i<MAX_ITERATION; i++)
{
npv = 0.00;
for (j=0; j<numOfFlows; j++)
{
denom = pow((1 + guessRate),j);
npv = npv + (cf[j]/denom);
}
/* Stop checking once the required precision is achieved */
if ((npv > 0) && (npv < PRECISION_REQ))
break;
if (old == 0)
old = npv;
else
old = new;
new = npv;
if (i > 0)
{
if (old < new)
{
if (old < 0 && new < 0)
highGuessRate = newguessRate;
else
lowGuessRate = newguessRate;
}
else
{
if (old > 0 && new > 0)
lowGuessRate = newguessRate;
else
highGuessRate = newguessRate;
}
}
oldguessRate = guessRate;
guessRate = (lowGuessRate + highGuessRate) / 2;
newguessRate = guessRate;
}
return guessRate;
}
I have attached the result for some value which are different in Excel and the above C language code.
Values: Output of Excel: -33.5%
1 = -18.5, Output of C code: 0.010 or say (1.0%)
2 = -18.5,
3 = -18.5,
4 = -18.5,
5 = -18.5,
6 = 32.0
Guess rate: 0.1
Since low_rate and high_rate are both positive, you're not able to get a negative score. You have to change:
#define LOW_RATE 0.01
to, for example,
#define LOW_RATE -0.5

Roundoff number to greater value in Objective C

I want to roundoff my number to greater value. for example if i have 234 i want to make it 300 and 4436 to 5000. I have tried it but i can roundoff my value not in hundred and thousants but in tens. like i have a value 7771 it roundoff to 7900 or 7800 but i want it in 8000.
int temp = lroundf([[arrayPercentage objectAtIndex:i]floatValue]);
maxPer = (((temp + 10)/10))*10;
How about this:
-(void)roundUpNumber:(NSInteger) num {
NSInteger numLength = [[NSString stringWithFormat:#"%ld",num] length];
NSInteger newNum = ceil(num/pow(10,numLength-1)) * pow(10,numLength -1);
NSLog(#"%ld",newNum);
}
int num, count = 0;
int originalNumber = 7771;
num = originalNumber;
while (num) {
num = num/10;
count ++;
}
int power = pow(10,(count -1));
int firstDigit = originalNumber / power;
int finalNumber = (firstDigit + 1)* power;
NSLog(#"final result : %d",finalNumber);

Round to "beautiful" value

guys, I'm making simple graph drawer and want to find beautiful values for horizontal lines.
For example, if I have value equals to 72089.601562, beautiful is 70000, or 75000. So, I think that beautifulNumber%5 = 0.
Have you any ideas?
How about this?
#import <math.h>
#import <stdio.h>
#define ROUNDING 5000
int beautify(float input)
{
// Cast to int, losing the decimal value.
int value = (int)input;
value = (value / ROUNDING) * ROUNDING;
if ((int)input % ROUNDING > ROUNDING / 2 )
{
value += ROUNDING;
}
return value;
}
int main()
{
printf("%d\n", beautify(70000.601562)); // 70000
printf("%d\n", beautify(72089.601562)); // 70000
printf("%d\n", beautify(76089.601562)); // 75000
printf("%d\n", beautify(79089.601562)); // 80000
printf("%d\n", beautify(70000.601562)); // 70000
return 0;
}
It depends whether you want a floor value, a ceiling value or just to round to the nearest 5000.
For a floor value:
int beautiful = (int)(floor(ugly / 5000.0) * 5000.0);
For a ceiling value:
int beautiful = (int)(ceil(ugly / 5000.0) * 5000.0);
For rounding:
int beautiful = (int)(round(ugly / 5000.0) * 5000.0);
For making graph lines, I'd probably find the minimum and maximum values you have to graph, start with a floor value for the minimum value and then add your desired interval until you have surpassed your maximum value.
For instance:
float minValue = 2.34;
float maxValue = 7.72;
int interval = 1;
NSMutableArray *horizLines = [NSMutableArray array];
int line = (int)(floor(minValue / interval) * interval);
[horizLines addObject:[NSNumber numberWithInt:line]];
do {
line = (int)(ceil(minValue / interval) * interval);
[horizLines addObject:[NSNumber numberWithInt:line]];
if (minValue >= maxValue) break;
minValue = minValue + interval;
}
Use as needed!
Well, it seems like you'd want it to scale based on the size of the number. If the range only goes to 10, then obviously rounding to the nearest 5,000 doesn't make sense. There's probably a really elegant way to code it using bit shifting but just something like this will do the trick:
float value = 72089.601562
int beautiful = 0;
// EDIT to support returning a float for small numbers:
if (value < 0.2) beautiful = int(value*100)/100.;
else if (value < 2.) beautiful = int(value*10)/10.;
// Anything bigger is easy:
else if (value < 20) beautiful = (int)value;
else if (value < 200) beautiful = (int)value/10;
else if (value < 2000) beautiful = (int)value/100;
else if (value < 20000) beautiful = (int)value/1000;
// etc
Sounds like what you want to do is round to 1 or perhaps 2 significant digits. Rounding to n significant digits is pretty easy:
double roundToNDigits(double x, int n) {
double basis = pow(10.0, floor(log10(x)) - (n-1));
return basis * round(x / basis);
}
This will give you roundToNDigits(74518.7, 1) == 70000.0 and roundToNDigits(7628.54, 1) == 8000.00
If you want to round to 1 or 2 digits (only 2 where the second digit is 5), you want something like:
double roundSpecial(double x) {
double basis = pow(10.0, floor(log10(x))) / 2.0;
return basis * round(x / basis);
}

Split a integer into its separate digits

Say I have an integer, 9802, is there a way I can split that value in the four individual digits : 9, 8, 0 & 2 ?
Keep doing modulo-10 and divide-by-10:
int n; // from somewhere
while (n) { digit = n % 10; n /= 10; }
This spits out the digits from least-significant to most-significant. You can clearly generalise this to any number base.
You probably want to use mod and divide to get these digits.
Something like:
Grab first digit:
Parse digit: 9802 mod 10 = 2
Remove digit: (int)(9802 / 10) = 980
Grab second digit:
Parse digit: 980 mod 10 = 0
Remove digit: (int)(980 / 10) = 98
Something like that.
if you need to display the digits in the same order you will need to do the module twice visa verse this is the code doing that:
#import <Foundation/Foundation.h>
int main (int argc, char * argv[])
{
#autoreleasepool {
int number1, number2=0 , right_digit , count=0;
NSLog (#"Enter your number.");
scanf ("%i", &number);
do {
right_digit = number1 % 10;
number1 /= 10;
For(int i=0 ;i<count; i++)
{
right_digit = right_digit*10;
}
Number2+= right_digit;
Count++;
}
while ( number != 0 );
do {
right_digit = number2 % 10;
number2 /= 10;
Nslog(#”digit = %i”, number2);
}
while ( number != 0 );
}
}
return 0;
}
i hope that it is useful :)