# Finding a solution when there are two piecewise functions at play

The goal is to mathematically figure out where is the point when the both of the diagrams are the same distance to the Y-axis.

The solution to such a problem can be obtain quite easily by just plotting the diagram and visually inspecting where there are equal distances to the left-hand plot and to the right-hand plot (of course with some error). But I wish to go to the next level, and find the exact value.

Currently I am stuck with NSolve and can't make the final step ...

(*points for the lefthand diagram*)
v1 = {0, 170};
v2 = {-3.33, 125.6};
v3 = {-4.548, 114};
v4 = {-14.371, 95};
v5 = {-20.551, 80};
v6 = {-22.651, 74};
v7 = {-27.3475, 27.5};
(*points for the righthand diagram*)
p1 = {17.0445, 170};
p2 = {17.0295, 169.9};
p3 = {14.6615, 168.3};
p4 = {11.6015, 153};
p5 = {10.252, 126.01};
p6 = {2.05, 85};
p7 = {1.8, 80};
p8 = {0, 20};
(*linear functions for the lefthand diagram*)
vv1 = LinearModelFit[{v1, v2}, {1, x}, x];
vv2 = LinearModelFit[{v2, v3}, {1, x}, x];
vv3 = LinearModelFit[{v3, v4}, {1, x}, x];
vv4 = LinearModelFit[{v4, v5}, {1, x}, x];
vv5 = LinearModelFit[{v5, v6}, {1, x}, x];
vv6 = LinearModelFit[{v6, v7}, {1, x}, x];
(*linear functions for the righthand diagram*)
pp1 = LinearModelFit[{p1, p2}, {1, x}, x];
pp2 = LinearModelFit[{p2, p3}, {1, x}, x];
pp3 = LinearModelFit[{p3, p4}, {1, x}, x];
pp4 = LinearModelFit[{p4, p5}, {1, x}, x];
pp5 = LinearModelFit[{p5, p6}, {1, x}, x];
pp6 = LinearModelFit[{p6, p7}, {1, x}, x];
pp7 = LinearModelFit[{p7, p8}, {1, x}, x];

a[x_] := Piecewise[{{vv1[x], -3.33 <= x <= 0}, {vv2[x], -4.548 <=
x <= -3.33}, {vv3[x], -14.371 <= x <= -4.548}, {vv4[
x], -20.551 <= x <= -14.371}, {vv5[x], -22.651 <=
x <= -20.551}, {vv6[x], -27.3475 <= x <= -22.651}}];

b[x_] := Piecewise[{{pp1[x], 17.0295 <= x <= 17.0445}, {pp2[x],
14.6615 <= x <= 17.0295}, {pp3[x],
11.6015 <= x <= 14.6615}, {pp4[x],
10.252 <= x <= 11.6015}, {pp5[x], 2.05 <= x <= 10.252}, {pp6[x],
1.8 <= x <= 2.05}, {pp7[x], 0 <= x <= 1.8}}];

Plot[{a[x], b[x]}, {x, -30, 30}]

NSolve[Abs[a[x]] == b[x], x]


you can get result as follows:

Reduce[a[-x] == b[x], x] // Quiet

(*x < 0 || x == 6.92894 || x > 27.3475*)


you can see that the logical solution is 6.93. to get that exactly use:

sol = x /. Solve[{a[-x] == b[x], 0 < x < 20}, x][[1]] // Quiet
(*6.92894*)


or

sol = x /. FindRoot[a[-x] == b[x], {x, 6}]
(*6.92894*)


to visualize the solution:

Plot[{a[x], b[x], a[-sol]}, {x, -30, 30}, Exclusions -> None,
Epilog -> {PointSize[0.02], Point[{{-sol, a[-sol]}, {sol, b[sol]}}]}]


• This is exactly what i am looking for. Thank you! Commented Dec 11, 2014 at 16:32