# PiecewiseExpand doesn't work as expected with a recursive function

In an effort to examine this question on Math.SE, I defined the following functions

c[n_, x_] := (a[n - 1, x] + b[n - 1, x])/4 + x/2;
a[n_, x_] :=
Return[If[n == 0, 0, t = c[n, x]; If[t > x, a[n - 1, x], t]]];
b[n_, x_] :=
Return[If[n == 0, 1, t = c[n, x]; If[t > x, t, b[n - 1, x]]]];


These functions work as expected and return the correct output. However, when I call PiecewiseExpand[a[2, x]] I get the output of

1/4 (1 + 2 x) if x >= 1/22
0 else


This is clearly wrong - a[2, 0.3] = 0.25 while $$\frac{1+2\cdot0.3}{4} = 0.4$$. For some reason, PiecewiseExpand is not working properly here. Why is this happening, and how can I fix this problem?

Edit: At the suggestion of Nasser, I changed the functions to

c[n_, x_] := (a[n - 1, x] + b[n - 1, x])/4 + x/2;
a[n_, x_] :=
If[n == 0, 0, t = c[n, x]; If[t > x, a[n - 1, x], t, "idk"], "idk1"];
b[n_, x_] :=
If[n == 0, 1, t = c[n, x]; If[t > x, t, b[n - 1, x], "idk"], "idk1"];


Now with PiecewiseExpand[a[1, x], {0 < x < 1}], the output is idk.

• it is because of this. If[t > x, a[n - 1, x], t] you need to use the If with 3 arguments version. If[t > x, a[n - 1, x], t, "do not know" ]. Since it is not able to decide if t>x when x is symbolic. It works with x is a number, since then it is able to decide. And why do you need to use all these Return for? Just get rid of them. – Nasser Apr 26 at 2:13
• After changing the if statement to that, PiecewiseExpand just returns the fourth argument ("do not know"). – Varun Vejalla Apr 26 at 2:24
• That is correct. That is the expected result. How would you decide if 2>x or not if x is symbolic? Not possible. This is your algorithm. So you need to figure what to do in this case. It works when x is number. These issues do not show up in say Matlab, because Matlab is all numbers. So no need for the 3 branch If. But in Mathematica it is needed. – Nasser Apr 26 at 2:27
• I had quick look at the link you showed. Notice it says for x∈(0,1) so x in that algorithm is a specific numerical value. Not symbolic. – Nasser Apr 26 at 2:44
• No, it is not an assumption., In the algorithm you are trying to implement, x has to be given and it must be a number between 0 and 1. can not be symbolic, Otherwise you can't do it. I said all what I can on this. May be someone else can provide better help. good luck. – Nasser Apr 26 at 3:50