Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Percentage difference of two numbers?

  1. Sep 15, 2005 #1
    I am doing a computer science course and one exercise is to show that two numbers are within 0.01% of each other.

    The first step is to ask how one would define the percentage difference between two numbers?

    I would define it as:
    [(larger number – smaller number)/ (|the number midway between the two numbers|)] * 100

    I think this way is better compared with other ways such as

    1. [(larger number – smaller number)/(|smaller number|)] *100
    or
    2. [(larger number – smaller number)/(|larger number|)] * 100

    Mainly because my way allows one to get the same percentage difference between for example, (4,6) and (-4,-6). While the other two ways does not.

    Using 1.
    (6 – 4)/4 = 50%
    (-4 – -6)/|-6| = 33%

    Using 2.
    (6 – 4)/6 = 33%
    (-4 – -6)/|-4| = 50%

    Preferred Method.
    (6 – 4)/5 = 40%
    (-4 – -6)/|-5| = 40%

    Do you have any other suggestions?

    Thanks
     
  2. jcsd
  3. Sep 15, 2005 #2
    Presumed that a, b are non-zero and both either positive or negative (at the same time). Then this should do it:

    return (max(a,b)/min(a,b) <= 1.0001 && min(a,b)/max(a,b) >= 0.9999);
     
  4. Sep 16, 2005 #3
    That was a good idea but in my case either a or b could be positive and negative so I could have (2,-3). So the way you suggested has problems with this case (otherwise it is more superior than my way). Do you have a better method to cope with this one positive, one negative case?
     
  5. Sep 16, 2005 #4
    A negative number can never lie within 0.01% of a positive number or vice versa. That just can't happen! So if (a,b) can be (2,-3) the problem don't make any sense! But you could try:

    return (abs(max(a,b)/min(a,b)) <= 1.0001 && abs(min(a,b)/max(a,b)) >= 0.9999);

    Note that before using this method you have to take care of the case where a or b equals 0. And why is that? Cause division with zero is undefined. If a equals 0 and b is non-zero they can't lie within 0.01% of eachother. But if a and b both equals 0 they will lie within eachother. So I'd use (instead of the one obove):

    return (a == b || a != 0 && b != 0 && abs(max(a,b)/min(a,b)) <= 1.0001 && abs(min(a,b)/max(a,b)) >= 0.9999);

    If a equals b it will stop there and return the value true (even for the case a=b=0). But if a does not equal b it will continue to check that a and b are non-zero. If someone of them are zero it will stop there and return the value false. If they are both non-zero it will simply continue to check if they are within 0.01% eachother.
    This way we don't have to use if/else.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook