methmal66/ip

Testing a function with a tolerance value

Closed this issue ยท 6 comments

Whats the point of using fabs() inside assert() as show in below examples?

assert(fabs(use_pythagoras_theorem(3.0, 4.0) - 5.0) < 0.001);
assert(fabs(use_pythagoras_theorem(5.0, 12.0) - 13.0) < 0.001);
assert(fabs(use_pythagoras_theorem(8.0, 15.0) - 17.0) < 0.001);

Thanks for your curiosity to create the first issue on my repo! Stay tuned. This issue will be replied soon

fabs() function in math.h finds the absolute value of a any given real number.

  • fabs(0) = 0
  • fabs(23.5) = 23.5
  • fabs(-234) = 235

  • In this case fabs() used to find the gap between the real output value and what we think it to be, as the gap is always a positive number. Then we check if that gap is lesser than a tolerance value. If that logical expression is true, that means we are receiving an approximate value to the expected value as the output of the function.

    Example

    use_pythagoras_theorem(3.0, 4.0) return a decimal number like 4.999999.
    then fabs(use_pythagoras_theorem(3.0, 4.0) - 5.0) simplifies to fabs(4.999999 - 5.0) then fabs(-0.000001) then finally to 0.000001 . Therefore assert(fabs(use_pythagoras_theorem(3.0, 4.0) - 5.0) < 0.001); means assert(0.000001 < 0.001).

    Any idea on using this with user inputs rather than pre-specified values?

    @pawan-live
    User inputs are used in the final executable code which is delivered to a client. So its not needed to have user inputs in test files as we they only run them once before the delivery process. Thats why test files are hard coded in most cases. Using per-specified values in test files is not a good practice though.

    Any idea on using this with user inputs rather than pre-specified values?

    Its better to create a new separate issue for that question