Message Boards Message Boards

0
|
3873 Views
|
5 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Recursion by Rule

Posted 4 years ago

How to do recursion by using Rule ?

Simple way.

Example :

   fact = x_ /; x > 1 :> x ((x - 1) /. fact);

  fib = x_ /; x > 1 :> ( (x - 1) /. fib) + ((x - 2) /. fib);

8 /. fib

21

6 /.fact 

120

POSTED BY: ismail ali
5 Replies
Posted 4 years ago

small test

Range[10] /. fact
{1, 2, 3, 8, 15, 48, 105, 384, 945, 3840}
POSTED BY: ismail ali
Posted 4 years ago

the rule of Factorial2

 fact = x_Integer :> If[x == 1 || x == 0, 1, x ((x - 2) /. fact)];
POSTED BY: ismail ali
Posted 4 years ago

Thanks, Hans Dolhaine for Hint.

The correct Rule:

fact = x_ :> If[x == 1!! x == 0, 1, x ((x - 1) /. fact)];
POSTED BY: ismail ali

Sounds good. But what is the role of Factorial2? Shouldn't it be

fact = x_ :> If[x == 1 || x == 0, 1, x ((x - 1) /. fact)];
POSTED BY: Hans Dolhaine

Looks cool.

But

fact = x_ /; x > 1 :> x ((x - 1) /. fact);

and

In[132]:= 0 /. fact

Out[132]= 0

when ( mathmatically correct ! )

In[134]:= 0!

Out[134]= 1
POSTED BY: Hans Dolhaine
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract