1

I am trying to translate some matlab code to C# and have hit a problem. Its a numerical algorithm and matlab sets a tolerance which is based on the eps() function.

The matlab documentation (http://www.mathworks.co.uk/help/matlab/ref/eps.html) says:

d = eps(X) is the positive distance from abs(X) to the next larger in magnitude floating point number of the same precision as X. X may be either double precision or single precision

As far as I can tell, there is no native C# function which does the same thing. I am a physicist by trade so the intricacies of floating point operations are not something I really know about. Can someone point me in the right direction?

tl;dr: How to calculate the equivalent of eps(x) in C#?

horchler
  • 18,384
  • 4
  • 37
  • 73
FakeDIY
  • 1,425
  • 2
  • 14
  • 23
  • 4
    It's called an [ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place) and the question has been answered before for C# [here](http://stackoverflow.com/questions/9485943/calculate-the-unit-in-the-last-place-ulp-for-doubles) and [here](http://stackoverflow.com/questions/1668183/find-min-max-of-a-float-double-that-has-the-same-internal-representation). – horchler Aug 13 '13 at 16:47
  • aha! If I'd known it was called ULP I may have found those...thanks! – FakeDIY Aug 13 '13 at 16:49
  • I am surprised that nobody mentioned Epsilon. In C# _float.Epsilon_ is 1.401298E-45; _double.Epsilon_ is 4.94065645841247E-324 (on my machine) – dr. rAI May 21 '18 at 06:53

1 Answers1

1

For completeness, you can compute eps yourself in matlab as follows:

x=1; p=0; y=1; z=x+y;
while x~=z
   y=y/2; p=p+1; z=x+y; 
end
eps_ = y*2
eps

output:

eps_ =

  2.2204e-016


ans =

  2.2204e-016

The code is from: Introduction to Scientific Computing, C. F. van Loan

Buck Thorn
  • 5,024
  • 2
  • 17
  • 27
  • 1
    While this is a good exercise for anyone learning about floating-point, note that this is not how `eps` or ULP in other languages is actually calculated under the hood or should be calculated in real code: [see here for efficient C code](http://en.wikipedia.org/wiki/Machine_epsilon#How_to_determine_machine_epsilon). – horchler Aug 13 '13 at 21:05