How to determine the value of X using Javascript

Asked

Viewed 798 times

-2

How can I find out the value of X taking into account that the base formula is this? And using Javascript only?

1056261433 * X² + 431977909 * X - 2.022 = 281860832

There are functions that do this or need to create, could you please guide me? The intention is to create a function in JS that gives the value of X .

  • This is a question about how to solve mathematical operation and not exactly a language resource. Javascript can like virtually any other language determine the "X" (variable) of an arithmetic calculus, if you create (or use an existing) function for it.

2 answers

2

To solve a second-degree equation like this one you can use to baskara formula.

If the factors multiplying the X and the X2 always be that of the question, don’t need to use Javascript. You can make the account in the calculator and get the two desired roots in hand. Gives X=-0.760057 or X=0.351089, according to Wolfram alpha

If the equation parameters can change then you can program the formula using Javascript. The only special function you would need is the Math.sqrt to remove the square root.

  • I searched through the net functions to accomplish this but the ones I found do not take into account the = 281860832 you have something?

  • 3

    If you subtract 281860832 from both sides of the equation you get 1056261433 * X² + 431977909 * X - 281860834.022 = 0. Maybe it’s a good idea to work on your algebra a little :)

1

As already said the hugomg, is a second-degree equation, and they all have the following form:

Ax2 + bx + c = 0

In your case:

a = 1056261433
b = 431977909
c = -281860832 - 2.022 = -281860834.022

These equations can be solved by Bhaskara’s formula:

inserir a descrição da imagem aqui
Image of the formula: Wikipedia

In Javascript, a simple implementation takes the values of a, b and c and returns the two possible results:

var a = 1056261433; 
var b = 431977909;
var c = -281860834.022;

function bhaskara(a, b, c) {
  
   var ret = [];
   var d = delta(a, b, c);
   ret[0] = ((b * -1) - Math.sqrt(d)) / (2 * a);
   ret[1] = ((b * -1) + Math.sqrt(d)) / (2 * a);
   return ret;
  
   // calcula o delta separadamente
   function delta(a, b, c) {
       return Math.pow(b, 2) - (4 * a * c); 
   }
  
}

document.body.innerHTML = bhaskara(a, b, c).join(', ');

The limitation of this code is that it does not deal with complex numbers, if the delta of the equation is negative. If you need to deal with this type of value, you would need to create a representation of complexes like arrays or objects, or use a library like the Math.js.

Browser other questions tagged

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