How to determine if a number is a percentage of another number

I am writing an iPhone code that fuzzily recognizes whether the line with the wire is straight. I get a bearing of two end points and compare it with 0, 90, 180 and 270 degrees with a tolerance of 10 degrees plus or minus. Right now I am doing this with a bunch of if blocks that seem super awkward.

How to write a function, which, given the bearing 0..360, the percentage tolerance (say, 20% = (from -10 ° to + 10 °)), and a right angle , for example, 90 degrees, does the bearing return within the tolerance?

Update: I may be too specific. I think a good, general function that determines if a number is a percentage of another number is useful in many areas.

For example: Is the number of swipeLength inside 10% of maxSwipe ? That would be helpful.

BOOL isNumberWithinPercentOfNumber(float firstN, float percent, float secondN) { // dunno how to calculate } BOOL result; float swipeLength1 = 303; float swipeLength2 = 310; float tolerance = 10.0; // from -5% to 5% float maxSwipe = 320.0; result = isNumberWithinPercentOfNumber(swipeLength1, tolerance, maxSwipe); // result = NO result = isNumberWithinPercentOfNumber(swipeLength2, tolerance, maxSwipe); // result = YES 

Do you see what I get?

+4
source share
3 answers

20% in decimal is 0.2. Just divide by 100.0 to get the decimal. Divide by 2.0 to get half the acceptable range. (Combined into a divider 200.0)

From there, add and subtract from 1.0 to get 90% and 110%. If the first number is between the ranges, then you have it.

 BOOL isNumberWithinPercentOfNumber(float firstN, float percent, float secondN) { float decimalPercent = percent / 200.0; float highRange = secondN * (1.0 + decimalPercent); float lowRange = secondN * (1.0 - decimalPercent); return lowRange <= firstN && firstN <= highRange; } 

Note: there are no errors for NaN or negative values. You want to add this for production code.

Update: so that the percentage includes both +/- ranges.

0
source
 int AngularDistance (int angle, int targetAngle) { int diff = 0; diff = abs(targetAngle - angle) if (diff > 180) diff = 360 - diff; return diff; } 

This should work for any two angles.

+4
source

Answer your clarified / new question:

 bool isNumberWithinPercentOfNumber (float n1, float percentage, float n2) { if (n2 == 0.0) //check for div by zero, may not be necessary for float return false; //default for a target value of zero is false else return (percentage > abs(abs(n2 - n1)/n2)*100.0); } 

To explain, you take the absolute difference between your test and target value and divide it by the target value (two “absent calls” make sure that it works with negative target and test numbers as well, but not with negative percentages / tolerances). This gives a percentage of the difference expressed as a decimal fraction, multiplies it by 100 to give a “total” expression of percent (10% = 0.10),

0
source

All Articles