1
$\begingroup$

I am writing a program that accepts 2D functions from users and graphs them to a window (it's part of a small game, so it's not just that, but that's the essence of my task). The functions can contain basic operators ($+$, $-$, $\times$, $\div$, ^), a few functions ($sin$, $cos$, $tan$, $abs$, $√$ as $sqrt$, $log$, $ln$), a few named constants ($e$, $\pi$), arbitrary constant numbers, and the single independent variable $x$. Functions and operators may be composed in arbitrary ways.

Let's have such a function $f(x)$ as an example for the rest of this question.

$f(x) = \frac{1}{-100(x-0.4999)}+0.4999$

(a steep quotient function centered around $(0.4999, 0.4999)$)

Normally, the graph should be plotted from $x = 0$ up to the first value of $x$ for which $f(x)$ is undefined (or until the line goes out of view, but I don't need help with that).

The problem I have is that my program uses numerical techniques to draw an approximation of the function. It samples functions at intervals of 0.0125 on the $x$ axis and connects the dots. Because of that, it only catches undefined values of $f(x)$ when $x$ is a multiple of 0.0125, which is not exactly suitable. In our example, $f(x)$ is undefined at $x=0.4999$, so my drawing function will simply connect the two points around it with a nearly vertical line.

I don't plan on making a full-blown symbolic solver as that would be completely overkill for my project. Are there numerical analysis techniques I could use to find undefined points on an arbitrary function, considreing that I only need to find the first one for which $x \geq 0$?

I have considered asking the question on Stack Overflow, but the question feels just too math-related for it.

  • 0
    I see, I think it is a very challenging problem!2012-10-07

1 Answers 1

2

I ended up using a more adaptive sampling algorithm. To do this, I implemented an algorithm to derive the functions my program receives.

Before, I had a fixed sample rate of 0.0125 for $x$. Now, instead, I estimate the required increment such that the arc length between the current point and the next is approximately 0.0125. To do so, I evaluate the derivative of the function at the given point to get a slope. By multiplying the cosine of its arctangent by 0.0125, I get that approximate $x$ increment.

$x_{n+1} = x_n + cos(tan^{-1}(f'(x_n)) \cdot 0.0125$

The real formula for arc length, $\int_b^a \! {\sqrt{1 + f'(x)^2}} \mathrm{d}x$, would require me to implement integration, and that's an order of magnitude harder than derivation.