If I have 2 functions as vars, f1 and f2 - how can I determine whether or not the 2 functions will behave the same for all inputs? That is, they will return the same value for all inputs.
-
4To really make sure you'd have to try all possible inputs. Otherwise, test a few inputs, and assume the rest will follow. – elclanrs Apr 08 '15 at 22:02
-
Could you post more of an example of what you're looking for? All I could say from this is that if they're returning a value you would just do (var1 == var2) assuming they're the same type. – zfrisch Apr 08 '15 at 22:02
-
Are the functions identical? Like are you trying to compare if they both reference the same location in memory or are at least identical in logic? Or do they achieve the same result in different ways? If it's more the former, check the accepted answer here: http://stackoverflow.com/questions/9817629/how-do-i-compare-2-functions-in-javascript – lintmouse Apr 08 '15 at 22:16
3 Answers
It is not going to be possible for arbitrary functions.
For example, consider the Collatz function (n becomes 3n+1 if n is odd or n/2 if n is even). It is hypothesised that all positive integers eventually end up in the cycle 4->2->1. Suppose that your functions are designed to indicate the cycle that the input reaches (or indicate if it never reaches a cycle). f1
might just print 4->2->1 but f2
might repeatedly apply the function until a cycle is detected (and have some other case for determining if it is not in a cycle). There are no currently known inputs where f1
and f2
give different answers but it is unknown whether such an input exists.

- 17,120
- 7
- 53
- 75
One way is to write function which compares the outputs of some other functions which have been given the same input argument(s). Possible Input arguments can be pushed into an array to ease the process. Something like...
var func1 = function(inputValue) {
// return some stuff
};
var func2 = function(inputValue) {
// return some stuff
};
var inputArray = [/* some input values */];
function compare(array) {
var isSame = false;
for (var i = 0; i < array.length; i++) {
if (func1(array[i]) === func2(array[i]) {
isSame = true
} else {
return i
}
}
return isSame
}
var result = compare(inputArray);
if (typeof result === 'number') {
alert('Comparison failed at inputArray['+result+'] : ' + inputArray[result])
} else {
alert('Comparison success!')
}
The compare()
fucntion returns two different types of result depending on the the if-condition. If all if-conditions are met we get a boolean
(true), otherwise the for-loop stops and returns the index number
where the comparison failed - which can then be used to point back to the input value that broke the chain.

- 1,801
- 16
- 24
No, you cannot. The number of possible inputs to the given functions is infinite. So unless you know about some relation between them, a finite number of values will guarantee nothing.

- 768
- 4
- 13