Function to calculate the distance between two points

Asked

Viewed 321 times

1

//D = raizQuadrada( (x2 - x1)² + (y2 - y1)²)
function calculoX(x1, x2){
    var x1 = parseInt(prompt("Digite o valor de x1: "));
    var x2 = parseInt(prompt("Digite o valor de x2: "));
    console.log("Valor de X1: " + x1);
    console.log("Valor de X2: " + x2);
    var x3 = Math.pow(x2, 2) - Math.pow(x1, 2);
    return x3;

}
 function calculoY(y1, y2){
    var y1 = parseInt(prompt("Digite o valor de y1: "));
    var y2 = parseInt(prompt("Digite o valor de y2: "));
    var y3 = (Math.pow(y2, 2)) - (Math.pow(y1, 2));
    console.log("Valor de Y1: " + y1);
    console.log("Valor de Y2: " + y1);
    return y3;
}

 function distancia(x, y){
    var res = Math.sqrt((x + y));
    return res;
}
var x = calculoX();
var y = calculoY();
var d = distancia(x, y);

document.write("Valor final é: " + d);

How can I improve this code?

Some entries give some errors in the final result (such as x1 = 7, x2= 4, y1 = 5, y2 = 5) and return me NaN, why does this happen?

Reference: PUCRS

  • 1

    What’s the idea of having function calculoX(x1, x2){ and then rewrite those variables x1, x2 within the function?

  • 2

    Vc is making "x2 squared minus X1 squared", which is different from "(x2 - X1) squared". The same for Y1 and Y2. I didn’t see the rest of the code to see if there were any more bugs, but I’d start there...

  • 2

    Another tip is to do the table test, because then you will realize that for X1=7 and x2=4, calculoX() returns 4 2 - 7 2 = -33. And since Y1 and Y2 are equal, calculoY() returns zero. Then vc calculates the square root of x + y (which is -33), and square root of negative number results in Nan

  • @hkotsubo confused me on the rule of mathematics, I thought that both were multiplied squared.

3 answers

3


The calculation is not being done in the right way:

Math.pow(x2, 2) - Math.pow(x1, 2);

Math.pow(x2, 2) calculates x2 squared, so actually you’re doing x2² - x1². But what you want is (x2 - x1)², then the right thing would be:

Math.pow(x2 - x1, 2);

The same goes for y1 and y2. And the way this calculation is done, x + y may result in a negative number (as is the case with the numbers you put in the question), and when the number is negative, Math.sqrt returns NaN.


Another detail is that you declare the function with two parameters:

function calculoX(x1, x2)

But within the function you overwrite those values, so they’re actually not serving anything. You have to decide whether to read the values within the function, or whether to read outside it and pass them as parameters.

Another thing, you noticed that the calculation made for x1 and x2 is the same that should be done for y1 and y2? So there’s no point in creating two practically identical functions. The idea of functions is precisely to perform something that must be done in the same way, and there may be some variation according to the values of the parameters. Then you could create a single function that receives a parameter indicating if I am working with the values of x or y (more or less as suggested in anderson’s response, with the detail that he did not correct the calculation):

function calculo(variavel){
    let x1 = parseInt(prompt(`Digite o valor de ${variavel}1: `));
    let x2 = parseInt(prompt(`Digite o valor de ${variavel}2: `));
    return Math.pow(x2 - x1, 2);
}

let x = calculo('x');
let y = calculo('y');

let distancia = Math.sqrt(x + y);
console.log(`Distância: ${distancia}`);


But maybe you don’t even need those functions, after all you just need this:

let x1 = parseInt(prompt('Digite o valor de x1: '));
let x2 = parseInt(prompt('Digite o valor de x2: '));
let y1 = parseInt(prompt('Digite o valor de y1: '));
let y2 = parseInt(prompt('Digite o valor de y2: '));

let distancia = Math.sqrt( Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2) );
console.log(`Distância: ${distancia}`);

Oh yes, notice also that it does not matter to use x1 - x2 or x2 - x1, because as I’m squaring, the result will be the same.


If you want, you can even do a function to validate whether a number has actually been entered. For example:

function lerNumero(variavel) {
    while (true) {
        let valor = parseInt(prompt(`Digite o valor de ${variavel}: `));
        if (isNaN(valor)) {
            console.log('Valor não é um número');
        } else {
            return valor;
        }
    }
}

let x1 = lerNumero('x1');
let x2 = lerNumero('x2');
let y1 = lerNumero('y1');
let y2 = lerNumero('y2');

let distancia = Math.sqrt( Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2) );
console.log(`Distância: ${distancia}`);

Finally, you can still trade parseInt for parseFloat, if you want to accept decimal numbers.


And in the newer versions of the language, you can use the exponentiation operator ** (instead of Math.pow), recourse already supported by browsers:

let x1 = parseInt(prompt('Digite o valor de x1: '));
let x2 = parseInt(prompt('Digite o valor de x2: '));
let y1 = parseInt(prompt('Digite o valor de y1: '));
let y2 = parseInt(prompt('Digite o valor de y2: '));

// elevar a 0.5 é o mesmo que obter a raiz quadrada
let distancia = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5;
console.log(`Distância: ${distancia}`);

  • 1

    Excellent @hkotsubo explanation, and showed where I am/was wrong. + 1

2

Just to complement the answer that already explains some points in relation to the original code, it is possible to shorten even further the part of the calculation of the distance itself.

This is because, strictly speaking, Javascript itself already implements the calculation to determine this distance. The function is qualified as hypot, in the overall object Math.

As the distance between two points is nothing more than the hypotenuse of a rectangular triangle, we can use Math.hypot. Is trivial:

Math.hypot(x1 - x2, y1 - y2)

In the example already provided:

let x1 = parseInt(prompt('Digite o valor de x1: '));
let y1 = parseInt(prompt('Digite o valor de y1: '));
let x2 = parseInt(prompt('Digite o valor de x2: '));
let y2 = parseInt(prompt('Digite o valor de y2: '));

let dist = Math.hypot(x1 - x2, y1 - y2);
console.log(`Distância: ${dist}`);

0

Hello, you can improve the code by reusing the calculation function.

And NAN occurs because the value reported for Math.sqrt is negative, using Math.abs can be removed the signal from the number, always returning the positive value.

function calculo(letter){
    var x1 = parseInt(prompt(`Digite o valor de ${letter}1: `));
    var x2 = parseInt(prompt(`Digite o valor de ${letter}2: `));
    var x3 = Math.pow(x2, 2) - Math.pow(x1, 2);
    return Math.abs(x3);
}

function distancia(x, y){
    var res = Math.sqrt(x + y);
    return res;
}
var x = calculo("x");
var y = calculo("y");
var d = distancia(x, y);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.