Recursive fibonacci-like functions in Sympy - recursion

How can I define a recursive function in Sympy, like the fibonacci function so its engine can perform simplifications on it?
I.e. f(0)=0, f(1)=1, f(x)=f(x-1) + f(x-2)
It looks like Sympy's Piecewise might be needed, but I don't see how to express recursion.
I got this far:
from sympy import *
x=symbols('x')
f=Function('f')
f=Piecewise((0, Eq(x,0)), (1, Eq(x,1)), (f(x-1)+f(x-2), True))
f
f.subs(x,10)
The evaluation of line f looks fine:
But the last line evaluates to f(8)+f(9) which is of course not what I want because it cannot be simplified further.
I know that the fibonacci function is already defined, but I need it for something similar not for fibonacci itself.

You could try rsolve (though the version I tested doesn't recognize the Fibonacci function) but if that fails you might consider a memoized function:
>>> from sympy.strategies.core import memoize
>>> #memoize
... def f(x):
... if x == 0:return 0
... if x == 1:return 1
... return f(x-1)+f(x-2)
>>> f(10)
55
>>> f(8)+f(9)
55

Related

Expression manipulation for calculus in julia

I am currently trying some functionalities of Julia regarding symbolic expressions. Coming from Matlab I searched the documentation for symbolic something with little success until I found some info about the expr = :(<content>) notation.
I started with the declaration of my first function : fun1 = :(1-x) which works fine. However, I need to reuse my expression or manipulations of it afterwards.
After searching a bit, I still did not find a way to say e.g fun2 = -fun1. How does one manipulate expressions once they are declared?
EDIT My example statement being a bit restrictive, an additional case would be the construction of a array of expression using pre-declared expresions as in exprarray = [fun1 0 -2*fun2+3]
you can interpolate expressions with $:
julia> fun1 = :(1-x)
:(1 - x)
julia> fun2 = :(-$fun1)
:(-((1 - x)))
EDIT
The same works for the array :
julia> exprarray = :([$fun1 0 -2*$fun2+3])
:([1 - x 0 -2 * -((1 - x)) + 3])

prolog factorial recursion giving expression as output

I've written a prlog recursive factorial clause which is:
factorial(X,Y):-
(X>1)
-> factorial(X-1,X*Y)
; write(Y).
The problem is, for any valid call[for example, factorial(5,1). ], it is giving an expression rather than a value[(5-1-1-1)* ((5-1-1)* ((5-1)* (5*1)))]. How can I get a value rather than an expression.
The comment by #lurker is a bit simplistic. Comparison operators do evaluate expressions. So, your code could be made to work:
factorial(X,Y):- X>1 -> factorial(X-1,F), Y=X*F ; Y=1.
?- factorial(5,X),F is X.
X = 5*((5-1)*((5-1-1)*((5-1-1-1)*1))),
F = 120.

Define Piecewise Functions in Julia

I have an application in which I need to define a piecewise function, IE, f(x) = g(x) for [x in some range], f(x)=h(x) for [x in some other range], ... etc.
Is there a nice way to do this in Julia? I'd rather not use if-else because it seems that I'd have to check every range for large values of x. The way that I was thinking was to construct an array of functions and an array of bounds/ranges, then when f(x) is called, do a binary search on the ranges to find the appropriate index and use the corresponding function (IE, h(x), g(x), etc.
It seems as though such a mathematically friendly language might have some functionality for this, but the documentation doesn't mention piecewise in this manner. Hopefully someone else has given this some thought, thanks!
with a Heaviside function you can do a interval function:
function heaviside(t)
0.5 * (sign(t) + 1)
end
and
function interval(t, a, b)
heaviside(t-a) - heaviside(t-b)
end
function piecewise(t)
sinc(t) .* interval(t,-3,3) + cos(t) .* interval(t, 4,7)
end
and I think it could also implement a subtype Interval, it would be much more elegant
I tried to implement a piecewise function for Julia, and this is the result:
function piecewise(x::Symbol,c::Expr,f::Expr)
n=length(f.args)
#assert n==length(c.args)
#assert c.head==:vect
#assert f.head==:vect
vf=Vector{Function}(n)
for i in 1:n
vf[i]=#eval $x->$(f.args[i])
end
return #eval ($x)->($(vf)[findfirst($c)])($x)
end
pf=piecewise(:x,:([x>0, x==0, x<0]),:([2*x,-1,-x]))
pf(1) # => 2
pf(-2) # => 2
pf(0) # => -1
Why not something like this?
function piecewise(x::Float64, breakpts::Vector{Float64}, f::Vector{Function})
#assert(issorted(breakpts))
#assert(length(breakpts) == length(f)+1)
b = searchsortedfirst(breakpts, x)
return f[b](x)
end
piecewise(X::Vector{Float64}, bpts, f) = [ piecewise(x,bpts,f) for x in X ]
Here you have a list of (sorted) breakpoints, and you can use the optimized searchsortedfirst to find the first breakpoint b greater than x. The edge case when no breakpoint is greater than x is also handled appropriately since length(breakpts)+1 is returned, so b is the correct index into the vector of functions f.

Julia: show body of function (to find lost code)

In the R-language I am able to declare a function and to see the body of the function like so:
> megafoobar = function(x){ return(x + 10000 )}
> body(megafoobar)
{
return(x + 10000)
}
Is something like this also possible in Julia? I wrote a function that was very useful and it is still in memory/callable but I forgot how I wrote it. I am hoping such a method exists in Julia so I can find out how I wrote it.
For functions defined in a package, you can use less or #less.
The former, takes a function name (and returns the first definition,
which need not be the one you want), the latter, a function call.
less(less) # First definition of less,
# with signature (String,Integer)
#less less(less) # Definition of less(f::Callable)
But this will not work with functions you defined yourself in the REPL.
For those, you can use code_typed, but it only returns the AST (abstract
syntax tree) of your code, which is less readable.
You also need to provide the type of the arguments,
because there can be several functions with the same name:
you can get them with methods.
f(x::Number) = x + 1
f(x::AbstractArray) = length(x)
methods(f)
# 2 methods for generic function "f":
# f(x::Number) at none:1
# f(x::AbstractArray{T,N}) at none:1
code_typed(f,(Number,)) # Give the argument types as a tuple
# 1-element Array{Any,1}:
# :($(Expr(:lambda, {:x}, {{},{{:x,Number,0}},{}}, :(begin # none, line 1:
# return x::Number + 1
# end))))
the answers said above are already good.
I personally use the good old ctrl+r in the REPL and write the name of the function as you define it to find the block of code when you define your function.

Factorial using recursion in C

We all know the program for this
int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}
But what is not clear to me is how the inner thing is happening?
How is it calculating 5*4*3*2*1 (if n is 5)
Please give a clear explanation on this.
Thanks.....
Mathematically, the recursive definition of factorial can be expressed recursively like so (from Wikipedia):
Consider how this works for n = 3, using == to mean equivalence:
3! == 2! * 3 == (1! * 2) * 3 == ((1) * 2) * 3
This can be derived purely symbolically by repeatedly applying the recursive rule.
What this definition does is first expand out a given factorial into an equivalent series of multiplications. It then performs the actual multiplications. The C code you have performs the exact same way.
What might help to understand it, is that when you are recursively calling the function, the new "cycle" will use N-1, not N.
This way, once you get to N==0, the last function you called will return a 1. At this point all the stack of functions are waiting for the return of the nested function. That is how now you exactly multiply the results of each of the functions on the stack.
In other words, you factorize the number given as input.

Resources