7.18 boolean evaluation (23.11.01)

7.18.1 PierLuigi Zezza

I am not able to understand the following behavior If I write

 > h:= proc(x): 
 >     if type(x, realcons) then 
 >          if x<=Pi then x^2 
 >          else x-1 
 >          fi; 
 >     else 
 >          'h(x)'; 
 >     fi; 
 > end:
 

I get the error message

 > h(2); 
Error, (in h) cannot evaluate boolean: 2-Pi <= 0
 

While if I write

 > h:= proc(x): 
 >     if type(x, realcons) then 
 >          if is(x<=Pi) then x^2 
 >          else x-1 
 >          fi; 
 >     else 
 >          'h(x)'; 
 >     fi; 
 > end:
 

I get

 > h(2); 
                                   4
 

I thought that writing if x<=Pi or if is(x<=Pi) was exactly the same, clearly I was wrong can someone explain me the difference

7.18.2 Robert Israel (26.11.01)

No, "if x <= Pi" and "if is(x <= Pi)" are not the same, and you have found a perfect example of this.

"if" by itself only does a very low-level Boolean evaluation of the condition. It can use < and <= to compare integers, fractions and floats but that’s about it. It can’t even handle algebraic constants, e.g. if 2 < sqrt(10) then ... will produce an error. Moreover, if a=b then ... with symbolic expressions only succeeds if a is literally the same as b, e.g. if (x+y)^2 = x^2 + 2*x*y + y^2 then A else B fi will return B.

"is" tries much harder to evaluate the condition, including the use of any assumptions that have been made.

7.18.3 Dr Francis J. Wright (28.11.01)

x<=Pi is just an expression that builds a data structure for some other Maple facility to interpret. If you use it in a boolean context (such as an "if" statement) then Maple implicitly applies evalb to it, but can only evaluate it to a boolean if both sides of the inequality are numerical. In your example, x has a numerical value (namely 2) but Pi is just a symbol; Pi only acquires a numerical value if a numerical evaluation function such as evalf is applied to it.

By contrast, the function "is" takes a more mathematical view and tries to perform the necessary simplification and evaluation. Here are some examples:

> x := 2: 
> x<=Pi; 
 
                               2 <= Pi 
 
> evalb(x<=Pi); 
 
                             2 - Pi <= 0 
 
> evalf(x<=Pi); 
 
                          2. <= 3.141592654 
 
> evalb(evalf(x<=Pi)); 
 
                                 true 
 
> is(x<=Pi); 
 
                                 true
 

However, beware that comparing floating-point approximations is generally unreliable.

See pages 189-190 of my book "Computing with Maple" (http://centaur.maths.qmw.ac.uk/CwM/) for a bit more detail on this general topic.