# User defined recursion - not limited

*** If you found the software useful donation is something you might consider ðŸ™‚ ***

## JAVA code

### Case 1: Fibonacci numbers using user defined recursive function

```import org.mariuszgromada.math.mxparser.*;
...
Function fib = new Function("fib(n) = if( n>1, fib(n-1)+fib(n-2), if(n > 0, 1, 0) )");
Expression e = new Expression("fib(10)", fib);

mXparser.consolePrintln("Res 1: " + e.getExpressionString() + " = " + e.calculate());
mXparser.consolePrintln("Res 2: fib(11) = " + fib.calculate(11));
```
```Res 1: fib(10) = 55.0
Res 2: fib(11) = 89.0
```

### Case 2: Number of recursive parameters is not limited - binomial coefficient definition using user defined recursive function

```import org.mariuszgromada.math.mxparser.*;
...
Function Cnk = new Function("Cnk(n,k) = if( k>0, if( k<n, Cnk(n-1,k-1)+Cnk(n-1,k), 1), 1)");
Expression e = new Expression("Cnk(10,3) - C(10,3)", Cnk);

mXparser.consolePrintln("Res 1: " + e.getExpressionString() + " = " + e.calculate());
mXparser.consolePrintln("Res 2: Cnk(10,3) = " + Cnk.calculate(10,3));
```
```Res 1: Cnk(10,3) - C(10,3) = 0.0
Res 2: Cnk(10,3) = 120.0
```

### Case 3:Â Mixing function parameters - part causing recursive calls, other part as 'typical' parameter. Below example is presenting definition of Chebyshev polynomial using recursive function.

```import org.mariuszgromada.math.mxparser.*;
...
Function T = new Function("T(n,x) = if(n>1, 2*x*T(n-1,x)-T(n-2,x), if(n>0, x, 1) )");
Argument k = new Argument("k = 5");
Argument x = new Argument("x = 2");

Expression e = new Expression("T(k,x) - ( (x + sqrt(x^2-1))^k + (x - sqrt(x^2-1))^k)/2", T, k, x);
mXparser.consolePrintln("Res : " + e.getExpressionString() + " = " + e.calculate());
```

### Case 4: Indirect recursion - approximating sin(x) and cos(x)

```import org.mariuszgromada.math.mxparser.*;
...
Constant a = new Constant("a = 0.001");
Function s = new Function("s(x) =  if( abs(x) < a, x, 2*s(x/2)*c(x/2) )", a);
Function c = new Function("c(x) =  if( abs(x) < a, 1, c(x/2)^2-s(x/2)^2 )", a);

Expression e1 = new Expression("sin(5)-s(5)", s);
Expression e2 = new Expression("cos(5)-c(5)", c);

mXparser.consolePrintln("Res 1: " + e1.getExpressionString() + " = " + e1.calculate());
mXparser.consolePrintln("Res 2: " + e2.getExpressionString() + " = " + e2.calculate());
```
```Res 1: sin(5)-s(5) = 0.0014644953426188323
Res 2: cos(5)-c(5) = -4.3256817118558777E-4
```

*** If you found the software useful donation is something you might consider ðŸ™‚ ***

Best regards,