Search code examples
c#mathoxyplot

OxyPlot draws circle incorrectly (with gap)


I typed this:

myModel.Series.Add(new FunctionSeries((x) => Math.Sqrt(16 - Math.Pow(x, 2)), -4, 4, 0.1, "x^2 + y^2 = 16") { Color = OxyColors.Red });
myModel.Series.Add(new FunctionSeries((x) => - Math.Sqrt(16 - Math.Pow(x, 2)), -4, 4, 0.1) { Color = OxyColors.Red });

And OxyPlot drew it:

enter image description here

How to fix it?


Solution

  • This is because

    Math.Sqrt(16 - Math.Pow(x, 2))
    

    returns NaN for x = 4 because 16 - Math.Pow(x, 2) is calculated by double precision. This means the result equals not exactly 0 (-3,5527136788005E-14 in this case). A negative square root like Math.Sqrt(-3,5527136788005E-14) is undefined like described at MSDN.

    You could fix it by prohibiting negative numbers. Just take the maximum of your calculation and 0 like

    Math.Sqrt(Math.Max(16 - Math.Pow(x, 2), 0))