Monday , 1 May 2017
Home » Miscellaneous » Recursive Lambda with Fixed Point Generator

Recursive Lambda with Fixed Point Generator

Reading Mads Torgersen old blog post on Recursive Lambda Expressions, I decided it was time for me to seriously play with his code and try out the fixed point generator to create recursive lambda expressions (together with the fact that I was sick and felt bored).

Taking lessons from that blog post, I created a reusable fixed point generator which we can use for anything that uses recursion. Here’s the code, simply.

Static Fix methods are the actual Fixed Point Generator as described in Mads’ blog. This simplifies the code and makes it reusable. The method at lines 11-14 shows how 2 different input can be used. I will be using this method for the sine and cosine lambda expressions I’ve written.

The factorial lambda expression is the same as in Mads’ blog. I’ve created both sine and cosine lambda expressions learning from how the fixed point generator works. I have to keep factorial as double instead of int because it’ll make the precision wrong.

I used the Taylor Series in order to generate the sine and cosine function. x is the angle in radians, and n is the number of recursion to do (i.e. the more recursion, the more precision).

The basic recursion is as follows:

So that’s that! Plug in your lambda expression into the Fix static method and you’re done, you’ve got recursion.

Further testing out whether if it actually works, here’s a simple testing code:

Here, what I do is I check my sine and cosine output with the actual Math.Sin and Math.Cos methods from the framework. It looks like it works well with n = 10 or higher, achieving the same precision as the framework.

That’s that. I will play around with more of this, and create more methods out of this.

I tried generalizing the method itself to make it look better and easier to read, but the limits of Generics in C# stopped me from doing anything further. Here’s what I tried to do, but failed of course.

If that was successful, then the code would have been reduced to simply like this.

Doesn’t that look better? If only, but there must be come other way to do this.

About Justin Lee

Leave a Reply