Message Boards Message Boards

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

How do I extract the condition from a conditional expression?

Posted 8 months ago

I have a calculation which at a certain point produces a conditional expression like

CE= (expression involving x) if 1<= x <= 3.

I want to extract the fact that the variable which is conditional is x, and that the bounds are 1 and 3. Then I can continue the calculation by getting the values of the expression when x is 1 and when x is 3.

I guess I could do this by turning CE into a character string, searching for "if" and so on. But is there an easier (non-acrobatic) way?

Thanks

POSTED BY: David Golber
5 Replies
Posted 8 months ago

Thanks for all these. Hans Milton's and Gianluca Gorni's suggestions certainly work. I'm not sure of Bill Nelson's. (In the meantime - not surprisingly - I've done what i needed in a completely different way.)

And here's a bit: If i write

e[x_] := ( Sqrt[1 - x^2] if - 1 <= x <= 1); 

Then

e[.5] gives -1 + 0.866025 if <= 0.5

But if i write

f[x_] := ConditionalExpression[Sqrt[1 - x^2], -1 <= x <= 1];

Then

f[.5] gives 0.866025
POSTED BY: David Golber

If you write

 ( Sqrt[1 - x^2] if - 1 <= x <= 1)

the if is interpreted as a symbolic variable with no meaning, that multiplies Sqrt[1 - x^2].

The if that you see when you do this

Solve[x^2 + y^2 == 1, y, Reals]

is for display only. It is not valid input syntax.

POSTED BY: Gianluca Gorni
Posted 8 months ago

One could use Apply to convert the conditional expression to a list:

ce = ConditionalExpression[x^f, 1 <= x <= 3]

List @@ ce
POSTED BY: Hans Milton

A little more directly, the condition is the second element of the expression ConditionalExpression[expr,cond]. You can extract it the same way you would with a list:

ConditionalExpression[1/(1 + n), Re[n] > -1][[2]]
POSTED BY: Gianluca Gorni
Posted 8 months ago

Pattern matching is usually the answer to questions like this, but pattern matching is pretty literal in what you ask for, whether it will successfully match and what it gives you.

Will this do some of what you want?

CE= ConditionalExpression[-Sqrt[1-x-x^2],Inequality[1,LessEqual,x,LessEqual,3]];
CE/.ConditionalExpression[val_,Inequality[lo_,LessEqual,x,LessEqual,hi_]]->{val,lo,hi}

which returns

{-Sqrt[1-x-x^2],1,3}

Asking how to get it to correctly identify the variable you want it to find that is within an unknown expression or even class of expressions and return to you is less literal than I can likely correctly answer with a first guess. Imagine if you were trying to write your string searching code to extract the correct variable name from my function if I knew the kinds of functions that I was going to use and you didn't.

POSTED BY: Bill Nelson
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