Let's say you have a function that takes both x and y, real numbers that are integers, as arguments.
What would you put inside that function, using only mathematical operators, so that no two given sequences of arguments could ever return the same value, be it any kind of value?
Example of a function that fails at doing this:
function myfunction(x,y){
return x * y;
}
// myfunction(2,6) and myfunction(3,4) will both return 12
// myfunction(2,6) and myfunction(6,2) also both return 12.
As already noted in comments, at the level of JavaScript numbers such a function can't exist, simply because assuming that we're working with integer-valued IEEE 754 binary64 floats there are more possible input pairs than possible output values.
But to the mathematical question of whether there is a simple, injective function from pairs of integers to a single integer, the answer is yes. Here's one such function that uses only addition and multiplication, so should fit the questioner's "using only mathematical operators" constraint.
First we map each of the inputs from the domain of integers to the domain of nonnegative integers. The polynomial map x ↦ 2*x*x + x will do that for us, and maps distinct values to distinct values. (Sketch of proof: if 2*x*x + x == 2*y*y + y for some integers x and y, then rearranging and factoring gives (x - y) * (2*x + 2*y + 1) == 0; the second factor can never be zero for integers x and y, so the first factor must be zero and x == y.)
Second, given a pair of nonnegative integers (a, b), we map that pair to a single (nonnegative) integer using (a, b) ↦ (a + b)*(a + b) + a. It's easy to see that this, too, is injective: given the value of (a + b)*(a + b) + a, I can recover the value of a + b by taking the integer square root, and from there recover a and b.
Here's some Python code demonstrating the above:
def encode_pair(x, y):
""" Encode a pair of integers as a single (nonnegative) integer. """
a = 2*x*x + x
b = 2*y*y + y
return (a + b)*(a + b) + a
We can easily check that there are no repetitions for small x and y: here we take all pairs (x, y) with -500 <= x < 500 and -500 <= y < 500, and find the set containing encode_pair(x, y) for each combination. If all goes well, we should end up with a set with exactly 1 million entries, one per input combination.
>>> all_outputs = {encode_pair(x, y) for x in range(-500, 500) for y in range(-500, 500)}
>>> len(all_outputs)
1000000
>>> min(all_outputs)
0
But perhaps a more convincing way to establish the injectivity is to give an explicit inverse, showing that the original (x, y) can be recovered from the output. Here's that inverse function. It makes use of Python's integer square root operation math.isqrt, which is available only for Python >= 3.8, but is easy to implement yourself if you need it.
from math import isqrt
def decode_pair(n):
""" Decode an integer produced by encode_pair. """
a_plus_b = isqrt(n)
a = n - a_plus_b*a_plus_b
b = a_plus_b - a
c = isqrt(8*a + 1)
d = isqrt(8*b + 1)
return ((2 - c%4) * c - 1) // 4, ((2 - d%4) * d - 1) // 4
Example usage:
>>> encode_pair(3, 7)
15897
>>> decode_pair(15897)
(3, 7)
Depending on what you allow as a "mathematical operator" (which isn't really a particularly well-defined term), there are tighter functions possible. Here's a variant of the above that provides not just an injection but a bijection: every integer appears as the encoding of some pair of integers. It extends the set of mathematical operators used to include subtraction, division and absolute value. (Note that all divisions appearing in encode_pair are exact integer divisions, without any remainder.)
def encode_pair(x, y):
""" Encode a pair of integers as a single integer.
This gives a bijective map Z x Z -> Z.
"""
ax = (abs(2 * x + 1) - 1) // 2 # x if x >= 0, -1-x if x < 0
sx = (ax - x) // (2 * ax + 1) # 0 if x >= 0, 1 if x < 0
ay = (abs(2 * y + 1) - 1) // 2 # y if y >= 0, -1-y if y < 0
sy = (ay - y) // (2 * ay + 1) # 0 if y >= 0, 1 if y < 0
xy = (ax + ay + 1) * (ax + ay) // 2 + ax # encode ax and ay as xy
an = 2 * xy + sx # encode xy and sx as an
n = an - (2 * an + 1) * sy # encode an and sy as n
return n
def decode_pair(n):
""" Inverse of encode_pair. """
# decode an and sy from n
an = (abs(2 * n + 1) - 1) // 2
sy = (an - n) // (2 * an + 1)
# decode xy and sx from an
sx = an % 2
xy = an // 2
# decode ax and ay from xy
ax_plus_ay = (isqrt(8 * xy + 1) - 1) // 2
ax = xy - ax_plus_ay * (ax_plus_ay + 1) // 2
ay = ax_plus_ay - ax
# recover x from ax and sx, and y from ay and sy
x = ax - (1 + 2 * ax) * sx
y = ay - (1 + 2 * ay) * sy
return x, y
And now every integer appears as the encoding of exactly one pair, so we can start with an arbitrary integer, decode it to a pair, and re-encode to recover the same integer:
>>> n = -12345
>>> decode_pair(n)
(67, -44)
>>> encode_pair(67, -44)
-12345
The encode_pair function above is deliberately quite verbose, in order to explain all the steps involved. But the code and the algebra can be simplified: here's exactly the same computation expressed more compactly.
def encode_pair_cryptic(x, y):
""" Encode a pair of integers as a single integer.
This gives a bijective map Z x Z -> Z.
"""
c = abs(2 * x + 1)
d = abs(2 * y + 1)
e = (2 * y + 1) * ((c + d)**2 * c + 2 * (c - d) * c - 4 * x - 2)
return (e - 2 * c * d) // (4 * c * d)
encode_pair_cryptic gives exactly the same results as encode_pair. I'll give one example, and leave the reader to figure out the equivalence.
>>> encode_pair(47, -53)
-9995
>>> encode_pair_cryptic(47, -53)
-9995
I'm no math wiz but found this question kinda fun so I gave it a shot. This is by no means scalable to large number since I'm using prime numbers as exponents and gets out of control really quick. But tested up to 90,000 combinations and found no duplicates.
The code below has a couple extra functions generateValues() and hasDuplicates() that is just there to run and test multiple values coming from the output of myFunction()
BigNumber.config({ EXPONENTIAL_AT: 10 })
// This function is just to generate the array of prime numbers
function getPrimeArray(num) {
const array = [];
let isPrime;
let i = 2;
while (array.length < num + 1) {
for (let j = 2; (isPrime = i === j || i % j !== 0) && j <= i / 2; j++) {}
isPrime && array.push(i);
i++;
}
return array;
}
function myFunction(a, b) {
const primes = getPrimeArray(Math.max(a, b));
// Using the prime array, primes[a]^primes[b]
return BigNumber(primes[a]).pow(primes[b]).toString();
}
function generateValues(upTo) {
const results = [];
for (let i = 1; i < upTo + 1; i++) {
for (let j = 1; j < upTo + 1; j++) {
console.log(`${i},${j}`)
results.push(myFunction(i,j));
}
}
return results.sort();
}
function hasDuplicates(arr) {
return new Set(arr).size !== arr.length;
}
const values = generateValues(50)
console.log(`Checked ${values.length} values; duplicates: ${hasDuplicates(values)}`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/8.0.2/bignumber.min.js"></script>
Explanation of what's going on:
Using the example of myFunction(1,3)
And the array of primes [2, 3, 5, 7]
This would take the 2nd and 4th items, 3 and 7 which would result in 3^7=2187
Using 300 as the max generated 90,000 combinations with no duplicates (However it took quite some time.) I tried using a max of 500 but the fan on my laptop sounded like a jet engine taking off so gave up on it.
If x and y are some fixed size integers (eg 8 bits) then what you want is possible if the return of f has at least as many bits as the sum of the number of bits of x an y (ie 16 in the example) and not otherwise.
In the 8 bit example f(x,y) = (x<<8)+y would do. This is because if g(z) = ((z>>8), z&255) then g(f(x,y)) = (x,y). The impossibility comes from the pigeon hole principle: if we want (in the example) to map the pairs (x,y) (of which there 2^16) 1-1 to some integer type, then we must have at least 2^16 values of this type.
function myfunction(x,y){
x = 1/x;
y = 1/y;
let yLength = ("" + y).length
for(let i = 0; i < yLength; i++){
x*=10;
}
return (x + y)
}
console.log(myfunction(2,12))
console.log(myfunction(21,2))
Based on your question and you comments, I understood the following:
You want to pass 2 real numbers into a function. The function should use mathematical operators to generate a new result.
Your question is, if there is any kind of mathematical equation/function you could use, that would ALWAYS deliver a unique result.
If that's so, then the answer is no. You can make your function as complicated as possible and get a result(c) using the two numbers (a & b).
In this case I would look for another combination which could give me the result(c) using the same equation/function. Therefore I would use the system of linear equation to solve this mathematical issue.
In general, a system with fewer equations than unknowns has infinitely many solutions, but it may have no solution. Such a system is known as an underdetermined system.
In our case we would have one equation which gives us one result and two unknowns, therefore it would have infinitely many solutions because we already have a solution, so there is no way for the system to have no solutions at all.
More about this topic.
Edit:
I just recognized that some of us understood the domain of the function in a different way. I was thinking about real numbers (R) but it seems many assumed you talk about integers (Z) only.
Well I guess
real integers
wasnt clear enough, at least for me.
So if we would use integers only, I have no idea if that is possible to always have different results. Some users suggested a topic about that here I am also interested to take a look into that too.
Im trying to figure out how to write a JavaScript program that computes and outputs the volume of a regular tetrahedron. This is how far I got but it seems to get a error and not compute the right numbers after.
The equation for the triangle is
v = a3
6 √ 2
Sorry about the code i dont know how to post things on here very effectively. So this is my variables
var a = parseFloat(document.getElementById('length').value);
var b = (a * a * a) / 6 * Math.sqrt(2)
You are very close. You are missing some parenthesis around 6 * Math.sqrt(2)
Your code is doing (a*a*a) / 6 and then multiplying that result by the square root of 2.
You can read up on Operator Precedence
var a = 4;
var b = (a * a * a) / (6 * Math.sqrt(2))
console.log(b);
You can also use Math.pow()
var a = 4;
var b = Math.pow(a,3) / (6 * Math.sqrt(2))
console.log(b);
Hmm I have an issue with roundings on the client side which is then validated in the backend and the validation is failing due to this issue. Here is the previous question Javascript and C# rounding hell
So what I am doing is:
On client side:
I have 2 numbers: 50 and 2.3659
I multiply them: 50 * 2.3659 //118.29499999999999
Round to 2 decimal places: kendo.toString(50 * 2.3659, 'n2') //118.29
In backend(C#):
I am doing the same: 50 and 2.3659
I multiply them: 50 * 2.3659 //118.2950
Round to 2 decimal places: Math.Round(50 * 2.3659, 2) //118.30
And validation is failing. Can I do something on the client side?
Can you try parseFloat and toFixed functions as follows :
var mulVal = parseFloat(50) * parseFloat(2.3659);
var ans = mulVal.toFixed(2);
console.log(ans);
Javascript Arithmetic is not always accurate, and such erroneous answers are not unusual. I would suggest that you use Math.Round() or var.toFixed(1) for this scenario.
Using Math.Round:
var value = parseFloat(50) * parseFloat(2.3659);
var rounded = Math.round(value);
console.log(rounded);
Prints 118 to the console.
Using toFixed() method:
var value = parseFloat(50) * parseFloat(2.3659);
var rounded = value.toFixed(1);
console.log(rounded);
Prints 118.3 to the console.
Note that using toFixed(2) will give the value as 118.29.
Hope this helps!
Haven't tested this extensively, but the function below should emulate the 'MidPointToEven' rounding:
function roundMidPointToEven(d, f){
f = Math.pow(10, f || 0); // f = decimals, use 0 as default
let val = d * f, r = Math.round(val);
if(r & 1 == 1 && Math.sign(r) * (Math.round(val * 10) % 10) === 5)
r += val > r ? 1 : -1; //only if the rounded value is odd and the next rounded decimal would be 5: alter the outcome to the nearest even number
return r / f;
}
for(let d of [50 * 2.3659, 2.155,2.145, -2.155, 2.144444, 2.1, 2.5])
console.log(d, ' -> ', roundMidPointToEven(d, 2)); //test values correspond with outcome of rounding decimals in C#
A friend showed me that (at least, in the google chrome console) the following statement prints true:
1/Math.pow(0.9999999999999999, Number.MAX_SAFE_INTEGER) === Math.E
And indeed, 1/Math.pow(0.9999999999999999, Number.MAX_SAFE_INTEGER) is 2.718281828459045.
This can't be a coincidence?!
Could someone explain what is going on behind the scenes to make this work?
According to wolfram alpha, the correct value should be approximately 1/0.40628 which is approximately 2.4613566998129373 -- very far off from Math.E. (I am assuming that wolframalpha is more precise in its calculations than javascript, but I may be wrong).
Any explanation would be appreciated.
Bonus: What is the true approximate mathematical value of that expression, I wonder?
I found this:
n = 0.0000000000000001
(1 - n)^MAX_INT = 1 + (MAX_INT choose 2) * n + (MAX_INT choose 3) * n^2 + ... + n^MAX_INT
but I have no idea how to approximate that.
I tested the above expression in wolfram alpha and got 2.46 as well.
pow(x, y) is typically computed as exp(log(x) * y), so let's start there.
We have:
x = 0.9999999999999999, which rounds to x = 1 - eps (where eps == 2^-53).
y = 2^53 - 1 i.e. y = 1 / eps (approximately).
So we're actually calculating exp(log(1 - eps) * 1/eps).
The Taylor series expansion of log(1 - k) is -k - k^2/2 - ..., but in our case all the higher-order terms will be truncated.
So we have exp(-eps / eps), or exp(-1), which is 1 / e.
Demonstration:
1 - 0.9999999999999999 // 1.1102230246251565e-16
Math.log(1 - 1.1102230246251565e-16) // -1.1102230246251565e-16
1 / Number.MAX_SAFE_INTEGER // 1.1102230246251568e-16
This arises from the original characterisation of e as:
Then using the property that:
MAX_SAFE_INTEGER = 253-1, and
0.9999999999999999 rounds to 1 - 2-53
then
1/(1-2-53) = 1 + 2-53/(1-2-53) = 1 + 1/(253-1)
Therefore,
1/(1-2-53)253-1 = [1 + 1/(253-1)]253-1
which is very close to e.
I am trying to port a formula from numbers (Mac OS 10) to javascript, the original formula is thus:
(1−(1+(C37÷100)÷C39)^−C45)÷((C37÷100)÷C39)
I have written this:
var calcValueOne = (1 - (1 + (yield/100) / coupon_frequency) Math.sqrt() - coupons_until_maturity) / ( (yield/100) / coupon_frequency);
where yield = C37 and coupon_frequency = C39 and coupons_until_maturity = C45
I am getting the following error:
SyntaxError: Unexpected identifier 'Math'. Expected ')' to end a
compound expression.
My mathematics is not to hot and transposing this in to Javascript is proving to be a huge challenge for me, can anyone post a solution to this please?
EDIT
#Musa kindly added a response but the number it is returning is not what I expect so I thought I would expand on the values to see if that helps.
yield (C37) == 9.89
coupon_frequency (C39) == 4.00
coupons_until_maturity (C45) == 15.00
The number I am expecting is 12.41 but I am getting -607.1703544847592 the javascript now looks like this:
var calcValueOne = (1 - Math.sqrt(1 + (yield/100) / coupon_frequency) - coupons_until_maturity) / ( (yield/100) / coupon_frequency);
Again for clarity this is the original (excel / numbers) formula:
The ^ sign is the exponent function not the square root so use Math.pow to calculate it
var yield = 9.89;
var coupon_frequency= 4.00;
var coupons_until_maturity = 15.00
var calcValueOne = (1 - Math.pow((1 + (yield/100) / coupon_frequency), - coupons_until_maturity)) / ( (yield/100) / coupon_frequency);
document.body.innerHTML = calcValueOne;