Difference between == and === in Mathematica - comparison

I was under the impression that = is an assignment, == is a numeric comparison, and === is a symbolic comparison (as well as in some other languages == being equal to and === being identical to. However, looking at the following it would appear that this is not necessarily the case...
In: x == x
Out: True
In: x === x
Out: True
In: 5 == 5
Out: True
In: 5 === 5
Out: True
In: x = 5
Out: 5
In: 5 == x
Out: True
In: 5 === x
Out: True
In: 5 5 == 5x
Out: True
In: 5 5 === 5x
Out: True
In: x == y
Out: x == y
In: x === y
Out: False
In: y = x
Out: 5
In: x == y
Out: True
In: x === y
Out: True
So what exactly is the difference between == and === in Mathematica? I have been looking at the documentation but I still don't quite understand it.

One important difference is that === always returns True or False. == can return unevaluated (which is why it's useful for representing equations.)
In[7]:= y == x^2 + 1
Out[7]= y == 1 + x^2
In[8]:= y === x^2 + 1
Out[8]= False
There are some interesting cases where == returns unevaluated that are worth being aware of while programming. For example:
In[10]:= {} == 1
Out[10]= {} == 1
which can affect things like If[foo=={}, <true>, <false>].

== and === are very similar in the sense that it returns True if the lhs and rhs are equal. One example where they differ is when you compare numbers in different representation formats.
In: 5.==5
Out: True
In: 5.===5
Out: False
Although they are the same numerically, (which is why == returns True), they aren't exactly identical.
FYI, they are different functions internally. == is Equal, whereas === is SameQ.

Equal refers to semantic equality whereas SameQ is syntactic equality. For instance, Sin[x]^2+Cos[x]^2 and 1 are the same number, so they are equal semantically. Since this can not be determined without more transformations, Equal returns unevaluated. However, actual expressions are different, so SameQ gives False.
Sin[x]^2 + Cos[x]^2 == 1
Sin[x]^2 + Cos[x]^2 === 1
Simplify[Sin[x]^2 + Cos[x]^2 == 1]
Note that there's special handling of Real numbers, SameQ[a,b] can return True if a and b differ in the last binary digit. To do more restrictive identity testing, use Order[a,b]==0
a = 1. + 2^-52;
b = 1.;
a === b
Order[a, b]==0
SameQ can return True for expressions that are syntactically different because expression heads may sort arguments automatically. You can prevent automatic sorting by using holding attributes. For instance
c + d === d + c
SetAttributes[SameQ, HoldAll]
c + d === d + c

lhs===rhs yields True if the
expression lhs is identical to rhs,
and yields False otherwise.
and
lhs==rhs returns True if lhs and rhs
are identical.
Reference from here and here.

I direct you to section 2.5: Equality checks of an excellent book by Leonid Shifrin.

Related

Getting all solutions of a boolean expression in Z3Py never ends

Probably a basic question related to Z3: i am trying to get all solutions of a boolean expression, e.g. for a OR b, i want to get {(true, true),(false,true),(true,false)}
Based on other responses found, e.g. Z3: finding all satisfying models, i have the following code:
a = Bool('a')
b = Bool('b')
f1=Or(a,b)
s=Solver()
s.add(f1)
while s.check() == sat:
print s
s.add(Not(And(a == s.model()[a], b == s.model()[b])))
The issue is that it enters an infinite loop as at the second iteration: the constraint a == s.model()[a] is evaluated to false b/c s.model()[a] does not exist anymore.
Can someone tell what i am doing wrong?
I would advice you to try writing your loop like this instead:
from z3 import *
a = Bool('a')
b = Bool('b')
f1 = Or(a,b)
s = Solver()
s.add(f1)
while s.check() == sat:
m = s.model()
v_a = m.eval(a, model_completion=True)
v_b = m.eval(b, model_completion=True)
print("Model:")
print("a := " + str(v_a))
print("b := " + str(v_b))
bc = Or(a != v_a, b != v_b)
s.add(bc)
The output is:
Model:
a := True
b := False
Model:
a := False
b := True
Model:
a := True
b := True
The argument model_completion=True is necessary because otherwise m.eval(x) behaves like the identity relation for any x Boolean variable with a don't care value in the current model m and it returns x as a result instead of True/False. (See related Q/A)
NOTE: since z3 kindly marks don't care Boolean variables, an alternative option would be to write your own model generator that auto-completes any partial model. This would reduce the number of calls to s.check(). The performance impact of this implementation is hard to gauge, but it might be slightly faster.

F# Function where x is divisible by 2 or 3 but not 5

I have a function that determines whether a value is divisible by 2 or 3, but **NOT** 5:
let ttnf x =
if (x % 2 = 0) || (x % 3 = 0) && not(x % 5 = 0) then true
else
false
I'm getting a weird response from Visual Studio 2015 in the interactive panel.
I execute the above code in the F# interactive panel then enter say...
ttnf 15
Hit enter, nothing...
hit alt + enter then it returns it on the second time.
Any idea why it isn't returning true/false from entering:
ttnf 15
The first time?
Thanks.
#ildjarn commented about the error in your code, but about F# interactive's behavior: when you type code directly into fsi, you need to terminate each declaration with ;; to tell fsi to interpret it, otherwise it will just wait for you to continue your input (as you experienced). So:
> let ttnf x =
if (x % 2 = 0 || x % 3 = 0) && not(x % 5 = 0) then true
else
false;;
val ttnf : x:int -> bool
> ttnf 15;;
val it : bool = false
>

Ruby on Rails function defined failed tests

I have defined a function that takes in a number and returns true if it is a
power of 2. Otherwise, return false:
def is_power_of_two?(num)
n = 0
res = false
if num % 2 == 0
while 2^n <= num
if 2^n == num
res = true
end
n += 1
end
end
puts(n.to_s)
return res
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts('is_power_of_two?(1) == true: ' + (is_power_of_two?(1) == true).to_s)
puts('is_power_of_two?(16) == true: ' + (is_power_of_two?(16) == true).to_s)
puts('is_power_of_two?(64) == true: ' + (is_power_of_two?(64) == true).to_s)
puts('is_power_of_two?(78) == false: ' + (is_power_of_two?(78) == false).to_s)
puts('is_power_of_two?(0) == false: ' + (is_power_of_two?(0) == false).to_s)
However, my test results turn out to fail four out of five:
0
is_power_of_two?(1) == true: false
16
is_power_of_two?(16) == true: false
64
is_power_of_two?(64) == true: false
77
is_power_of_two?(78) == false: false
0
is_power_of_two?(0) == false: true
The result printed out seems to match what's expected, however, the tests still failed. Does anyone know why this happened?
if you expecting ^ to calculate the power then that is wrong ^ is XOR to calculate power use **
2^2 # 0
2**2 # 4
You always want to check if it is true that it is a power of two, this way it returns false when it is not a power of two.
This feels like a homework question so I'm not going to give you the exact answer, but this should nudge you in the correct direction.
As mohamed-ibrahm says, you're using the wrong operator.
The caret is a bitwise XOR operation. So 2^3 == 1 (because decimal 2 is 010 in binary and decimal 3 is 011 in binary and as all bits are the same except the last, the result is 001 or decimal 1).
Exponentiation is done by double asterisks, so 2**3 == 8
Here's a description of the various operators.
http://www.tutorialspoint.com/ruby/ruby_operators.htm

How to make a message repeat

I'm making a code just to test some things out
print('Hello! What is your name?')
name = io.read()
print('Hello '..name..'!')
repeat
print('What does a mute person say?')
say = io.read()
x = 'Nothing'
z = 'nothing'
if say == x then
print('Correct!')
elseif say == z then
print('Correct!')
else
print('Incorrect! Guess Again!')
end
until say = x or z
Everything works fine when I test it but if the answer is incorrect you cant try to answer again. Probably a stupid question but, is there anyway to make the question repeat when the answer is incorrect?
The loop condition say = x or z shouldn't compile, use == to test equality, not =.
That's not enough, say == x or z is equivalent to say == x because x or z has the value of x if x is not nil or false.
repeat
-- read say
until say == x or say == z

Lua Prime Number Checker

Here is my Lua code for taking user input, and checking if the number entered is prime. My issue is that the program thinks that any even number is not prime, and any odd number is.
print("Enter a number.")
local number = io.read("*n")
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
return true
end
end
if prime(number) == true then
print("Your number is prime!")
end
if prime(number) == false then
print("Your number is not prime!")
end
Move return true out of the loop.
Hence:
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
end
return true
end
You return true too soon. You return true as soon as any i meets the condition. You must place the return after the loop.
I know it's an old post but since it's near the top on google I figured it can't hurt to post up my prime finder. It basically does a few simple checks of the obvious stuff and then loops through whats left in a similar fashion to the first example in Jon Ericson' post. Haven't benchmarked it but it seems to cope well enough.
--returns true if prime
function isPrime(n)
local n = tonumber(n)
--catch nil, 0, 1, negative and non int numbers
if not n or n<2 or (n % 1 ~=0) then
return false
--catch even number above 2
elseif n>2 and (n % 2 == 0) then
return false
--primes over 5 end in 1,3,7 or 9
--catch numbers that end in 5 or 0 (multiples of 5)
elseif n>5 and (n % 5 ==0) then
return false
--now check for prime
else
--only do the odds
for i = 3, math.sqrt(n), 2 do
--did it divide evenly
if (n % i == 0) then
return false
end
end
--can defeat optimus
return true
end
end
If you are going to be checking primality, you might as well pick an efficient algorithm. As one answer (cryptically) pointed out, all even numbers greater than 2 are not prime. Therefore, you can short-circuit the check for half the numbers, which doubles the speed to check any particular number:
function check_prime (x)
-- Negative numbers, 0 and 1 are not prime.
if x < 2 then
return false
end
-- Primality for even numbers is easy.
if x == 2 then
return 2
end
if x%2 == 0 then
return false
end
-- Since we have already considered the even numbers,
-- see if the odd numbers are factors.
for i = 3, math.sqrt(x), 2 do
if x%i == 0 then
return false
end
end
return x
end
There are all sorts of optimizations we could apply, but let's take a shot at doing this in a more Lua manner:
function sieve (x)
if x < 2 then
return false
end
-- Assume all numbers are prime until proven not-prime.
local prime = {}
prime[1] = false
for i = 2, x do
prime[i] = true
end
-- For each prime we find, mark all multiples as not-prime.
for i = 2, math.sqrt(x) do
if prime[i] then
for j = i*i, x, i do
prime[j] = false
end
end
end
return prime
end
To use the sieve function:
prime = sieve(number)
if prime[number] then
print("Your number is prime!")
else
print("Your number is not prime!")
end
In my tests, the sieve version is about 6 times faster than the previous algorithm for generating all the primes less than 1 million. (Your mileage may vary.) You can easily check the primality of all numbers less than number at no extra cost. On the other hand, it uses more memory and if you really want check the primality of just one number, it's less efficient.
I would check for primes by dividing the number with 2 and checking if the floor of the division is equal to the division. It looks like this.
if (input/2 == math.floor(input/2)) then
print("is prime")
else
print("is not prime")
end

Resources