Basic javascript solving quadratic equations - javascript

Very new programmer, trying to make a quadratic equation solver in javascript.
//QuadSolver, a b c as in classic ax^2 + bx + c format
function quadsolve(x, a, b, c) {
var sol = (
((a * (x * x)) + (b * x)) + c
)
}
//Test
console.log(quadsolve(1, 1, 1, 0))
In the console, it outputs "undefined". Would this be the correct way to go about solving the problem? If so, how would I get a value instead of undefined? Thanks!

Like the others said you need to use the "return" keyword to return a value. Are you trying to find the zeros of the equation? If so here is the numeric solution:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-mml-chtml.js">
</script>
</head>
<body>
<h2>Quadratic Equation</h2>
<p>This is an example of the numerical solution of a quadratic equation using Ceres.js</p>
<p>
Problem Statment: find x when \(f(x)=0\)
\[f(x) = a*x^2+b*x+c\]
</p>
<textarea id="demo" rows="40" cols="170">
</textarea>
<script type="module">
import {Ceres} from 'https://cdn.jsdelivr.net/gh/Pterodactylus/Ceres.js#master/Ceres-v1.5.3.js'
var fn1 = function(x){
let a = 1
let b = -1
let c = 1
return a*x[0]*x[0]+b*x[0]+c //this equation is of the form f(x) = 0
}
let solver = new Ceres()
solver.add_function(fn1) //Add the first equation to the solver.
solver.promise.then(function(result) {
var x_guess = [1] //Guess the initial values of the solution.
var s = solver.solve(x_guess) //Solve the equation
var x = s.x //assign the calculated solution array to the variable x
document.getElementById("demo").value = "The solution is x="+x+"\n\n"+s.report //Print solver report
solver.remove() //required to free the memory in C++
})
</script>
</body>
</html>

Related

What is the definition of the natural logarithm? - Finding the value of natural logarithm using codes

I have created an algorithm for the base of the natural logarithm with HTML and JS. And this is the code:
HTML: bonl.html
<html>
<head>
<title>bonl</title>
</head>
<body>
<script src="bonl.js"></script>
<input type="number" id="entered">
<input type="button" value="run" onclick="calculate()">
<div id="bonl">
</body>
</html>
and Javascript: bonl.js
function calculate() {
var x = document.getElementById('entered').value;
console.log(x);
var e = (1 + (1/x))**x;
console.log(e);
document.getElementById('bonl').innerHTML = e;
}
First, you assign a number value to <input type="number" id="entered">, and click the button named 'run'. After that, var x in bonl.js will be equal to the number assigned to 'entered'. Then, according to the definition of the base of the natural logarithm (e = lim x->inf (1+(1/x)**x)), the Javascript file will calculate the e. And the result will be displayed by <div id="bonl">.
I hope you noticed that as the value of the x gets larger, javascript file calculates the base of the natural logarithm more accurately.
However, I entered about 10 quadrillion in <input type="number" id="entered">, and I've got the result of 1 instead of 2.71828.., although I get 2.71828 when I enter 100 trillion in <input type="number" id="entered">.
Is my computer dumb to calculate e, or is there an error in my code, or is e = 1?
Yes, your computer is dumb. It can only operate floating point numbers below 2^53. When you go above that, it loses the precision and 1 + small number becomes just 1:
for (let pow = 1; pow < 60; pow++) {
let n = 2 ** pow;
console.log('2^', pow, 'small=', 1 + 1/n, 'e=', (1 + 1/n)**n)
}
Can we do better than that? Yes, we can! Instead of computing e using floating point numbers, let's compute some_big_number * e using Big Integers, which, unlike floats, have unlimited precision. Using BigInts we can compute as many terms of the power series as we want:
let BIG = 10n ** 100n
let f = 1n
let e = BIG
let n = 1n
while (1) {
f = f * n
let eNext = e + BIG / f
if (eNext === e) {
document.write(`e = ${e} <br>`)
document.write(`terms = ${n} <br>`)
break
}
e = eNext
n += 1n
}

How to generate set of arrays when clicking button, without disappearing the first one?

Im trying to learn js. Im starting playing with array by generating 6 combination numbers. This is working but i dont know how to output another combinations when I click the button. Any comment is appreciated. THanks
function getRandomNumber() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var arr = [];
while(arr.length < 8){
var myrandomnumber = Math.floor(Math.random(x) * y + 1);
if(arr.indexOf(myrandomnumber) === -1) arr.push(myrandomnumber);
}
if (x==""){
alert("Please enter a number");
}
else if (y==""){
alert("Please enter a number");
}
else{
document.getElementById("ok").innerHTML = arr;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>RANDOM NUMBER JS</title>
<meta name="" content="">
<link rel="stylesheet" href="css/css/bootstrap.css">
<link rel="stylesheet" href="css/cssextra/csse1.css">
<script src="customscript.js"></script>
</head>
<body class="bg-light">
<br>
<p id="demo">Random Number</p>
<br><br>
<input type="number" id="num1" name="one"/ >
<input type="number" id="num2" name="two"/ >
<button onclick="getRandomNumber();">Generate random number</button >
<p id="ok"></p><br>
<p id="okok"></p>
</body>
</html>
Accumulate results
A easy yet crude solution would be appending the current text with <br> for line breaks:
const p = document.getElementById("ok");
p.innerHTML = p.innerHTML + (p.innerHTML === "" ? "" : "<br>") + arr.join(", ");
But this approach will notoriously perform badly as the text grows larger.
If you change the p elements into:
<div id="ok" class="text-container">
And replace the script's document.getElementById("ok").innerHTML = arr; into:
const p = document.createElement("p");
p.textContent = arr.join(", ");
document.getElementById("ok").appendChild(p);
And add css:
.text-container {
margin-top: 1em;
}
.text-container > p {
margin: 0;
}
Then you should have something working.
Also there are some things to address:
Math.random()
The function Math.random() does not take arguments, so your variable x does not have any effect.
If the intention is to x and y as a minimum and maximum value, try this from Math.random() - JavaScript | MDN:
function getRandomInt(min, max) {
var min = Math.ceil(min);
var max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
The min is inclusive and the max is exclusive. If x = 0 and y = 10, and you want the range to be [0-10], you can do getRandomInt(x, y + 1).
Make sure min is not greater than max.
Prevent infinite loop
Your loop will get stuck if the amount of possible unique integers is smaller than the number of array elements required for it to end.
More user input semantics
Variables x and y are tested before writing out the numbers, but after they have already been used to generate the numbers. In other words, the number creation process should be moved into the else block.
innerHTML expects a string and you are setting the array.
use document.getElementById("ok").innerHTML = arr.join(' ');
this will concatenate each element in the array with a space as glue

"unexpected console statement no-console"

I'm getting this error in Brackets.
I want to stress the fact that it's literally the second time I opened a JS file.
As I stressed It I want also to emphasize the fact that I have no clue what Eslint and node.js are.
All the fixes on the StackOverflow and other sites assume knowing how abovementioned entities work.
Please help to a complete newb to fix the problem and learn something new.
Thank you in advance!
Here's the piece of code, but I don't think it will help with anything.
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<h1>Javascript starter</h1>
<script src=Script.js> </script>
</body>
</html>
Javascript:
var now = 2018;
var yearJohn = 1989;
var fullAge = 18;
//Multiple operators
var isFullAge = now - yearJohn >= fullAge; //true
сonsole.log(isFullAge);
//Grouping
var ageJohn = now - yearJohn;
var ageMark = 35;
var average = (ageJohn + ageMark)/2;
console.log(average);
// Multiple assigments
var x, y;
x = y = (3 + 5) * 4 - 6; // 8 * 4 - 6 // 32 - 6 // 26
console.log(x, y);
// More operators
x *= 2;
console.log(x);
x += 10;
// eslint-disable-next-line no-console
console.log(x);
If it really is ESLint that is causing errors for this change, you can fix it by disabling the rule for that particular line:
// eslint-disable-next-line no-console
console.log(isFullAge);
Just add "no-console": 0 to the rules part of .eslintrc.js file.
E.g.
"rules": {
"no-console": 0
},
Add the following to your .eslintrc.js file
"no-console": ["error", { "allow": ["warn", "error"] }]
Install the "brackets-eslint" extension and reload your Brackets editor
Please try to change console.log to document.write
and then open your html file in browser
var now = 2018;
var yearJohn = 1989;
var fullAge = 18;
//Multiple operators
var isFullAge = now - yearJohn >= fullAge; //true
document.write(isFullAge);
//Grouping
var ageJohn = now - yearJohn;
var ageMark = 35;
var average = (ageJohn + ageMark)/2;
document.write(average);
// Multiple assigments
var x, y;
x = y = (3 + 5) * 4 - 6; // 8 * 4 - 6 // 32 - 6 // 26
document.write(x, y);
// More operators
x *= 2;
document.write(x);
x += 10;
// eslint-disable-next-line no-console
document.write(x);
Use console.warn(""); instead of console.log

Using Javascript, how do I target 3 variables and apply Math.random() to it?

I am trying to create a code here using Javascript only (without having anything in the HTML body) so that everytime I refresh it generates random numbers that add up.
I have already tried using Math.random() and innerHTML but I believe I am using it in the wrong place. Any help is greatly appreciated
<body>
<div id="mathProblem">
<!-- leave this div empty!-->
</div>
<script>
let myDiv = document.getElementById("mathProblem");
var x;
var y;
var z;
x = Math.random();
y = Math.random();
z = x + y
myDiv.innerHTML = "she made"+ x "cookies but ate " + y, "she has" + z "cookies left";
document.getElementById("mathProblem").innerHTML = z;
</script>
Finally, what I am basically trying to achieve is that every time I refresh, the X and Y variables are different and they add up to Z, hence resulting in a word problem.
There's just some typos in the innerHTML declaration.
myDiv.innerHTML = "she made"+ x + "cookies but ate " + y + "she has" + z +"cookies left";
Make sure you're concatenating the string right.
You can also use string interpolation which would look like this:
myDiv.innerHTML = `she made ${x} cookies but ate ${y} she has ${z} cookies left`;
notice the back-ticks `` instead of double quotes ""
So:
<body>
<div id="mathProblem"><!-- leave this div empty!--></div>
<script>
const myDiv = document.getElementById("mathProblem");
const x = Math.random();
const y = Math.random();
const z = x + y;
myDiv.innerHTML = `she made ${x} cookies but ate ${y} she has ${z} cookies left`;
</script>
</body>
You have a couple issues. First is that your javascript isn't completing as expected because of some missing plusses. The next is that you're assigning to the innerHTML twice. Finally, I imagine you're attempting to do integer math and express a logically correct sentence.
Give this explanation of Random a read and check out the differences between your code (with syntactic corrections) and my code at this JS Fiddle. You can play around with the JS there if you want to try new things. What it boils down to is this change:
let x = Math.floor(Math.random() * 10) + 1;
let y = Math.floor(Math.random() * 10) + 1;
let z = x + y;
document.getElementById("mathProblem").innerHTML = `she made ${z} cookies but ate ${y} she has ${x} cookies left`;
Math.random() does not provide cryptographically secure random
numbers. Do not use them for anything related to security. Use the Web
Crypto API instead, and more precisely the
window.crypto.getRandomValues() method.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
genRandomNumbers = function getRandomNumbers() {
  var array = new Uint32Array(2);
  window.crypto.getRandomValues(array);
 
  var randText = document.getElementById("myRandText");
var resultText = document.getElementById("result");
  randText.innerHTML = "The random numbers are: "
  for (var i = 0; i < array.length; i++) {
    randText.innerHTML += array[i] + " ";
  }
resultText.innerHTML = array[0] + array[1];
}
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto -->
<p id="myRandText">The random numbers are: </p>
<p id="result">
Result:
</p>
<button type="button" onClick='genRandomNumbers()'>Generate 2 random numbers and add</button>

Two javascript functions which work independently, but not together?

Background
I am attempting to write an exercise for Khan Academy. Their code is all available here: https://github.com/Khan/khan-exercises. This is my first time really programming anything, and I am learning html and js as I go basically just by looking at example code.
As part of this exercise I need to draw a "random function", and find it's zeros. I have written a zero finding algorithm (Cutting an interval in half repeatedly to zoom in on the zero.). I know some variant of newton's method is probably faster, but I wanted to insure convergence. My "random function" takes a set of points values and interpolates those points with a polynomial spline. Each of these work independently: I can graph my "random function" and I can use my zero finding algorithm to, say, approximate the square root of 2 (zero of x^2 - 2 on interval (1,2)). When I try to find zeros of my "random function" I run into trouble: My browser goes into an infinite loop or something. I can't even see what the errors are in the developer tools.
So my questions are basically:
What mistake have I made which is using up so much computing power here?
How could the functions work independently but not together?
How can I fix my code?
Since I am working within the whole knhan academy framework, there is too much going into my program to post all the relevant code (it uses Raphael to handle images, has prewritten code to make the exercises all have the same style, etc). I can give you the html code I have written and the .js file of functions that I have written.
<!DOCTYPE html>
<html data-require="math graphie graphie-helpers steveMath8">
<head>
<title>Piecewise-defined function</title>
<script src="../khan-exercise.js"></script>
</head>
<body>
<div class="exercise">
<div class="vars">
<var id = "n">randRange(2,4)</var>
<var id = "abscissas">makeXList()</var>
<var id = "ordinates">makeYList(-8,8,abscissas.length)</var>
<var id = "points">makeCoordinates(abscissas,ordinates)</var>
<var id = "f">(function(x){return niceFunction(x,points)})</var>
<!-- <var id = "f">(function(x){return x*x-n})</var>-->
<var id = zeros>locateZeros(f,abscissas)</var>
</div>
<div class="problems">
<div id="problem-type-or-description">
<p class="problem">You are going to have to answer 5</p>
<p class="question">Answer 5</p>
<div class="graphie" id="grid">
graphInit({
range: 10,
scale: 20,
tickStep: 1,
axisArrows: "<->"
});
a =style({
stroke: "red",
strokeWidth: 2
}, function() {
plot( function( x ) { return niceFunction(x,points);
}, [ -10, 10 ] );
});;
a.plot();
</div>
<p class="solution">5</p>
</div>
</div>
<div class="hints">
<!-- Any hints to show to the student. -->
</div>
</div>
</body>
$.extend(KhanUtil, {
//takes num and returns +1 if num>0 or -1 if num<0
steveSign: function(num){
return num && num/Math.abs(num)
},
// Approximates a root of f on the interval (xmin,xmax) by successively halving the interval.
steveRoot: function(f,xmin,xmax){
var l = xmin
var r = xmax
var z = 0
for (i=0;i<10;i++){
z = (l + r)/2
if (KhanUtil.steveSign(f(l)) == KhanUtil.steveSign(f(z))){ l = z}
else{r = z}
}
return z
},
//takes a function and a list of abscissas, and returns an array of zeros - one zero between each pair of abscissas that are of
//opposite sign
locateZeros: function(f,abscissas){
var len = abscissas.length
var list = []
var z = 0
for(i=0;i<len-1;i++){
var x0 = abscissas[i]
var x1 = abscissas[i+1]
var y0 = f(x0)
var y1 = f(y0)
if (KhanUtil.steveSign(y0) !== KhanUtil.steveSign(y1)){
z = KhanUtil.steveRoot(f,x0,x1)
list.push(KhanUtil.steveSign(f(x0)))
}
}
return list
},
steveCubic: function(x){return -Math.pow(x,3)/2+3*x/2},
//niceFunction is a C^1 function which connects the points in "points". It is designed to be used
//in my "curveSketchingIntuition" exercise. Every point in the "points" will have 0 slope, except the first and last point.
niceFunction: function(x,points){
len = points.length
var x1 = points[0][0]
var x2 = points[1][0]
var y1 = points[0][1]
var y2 = points[1][1]
var k = (y1 - y2)/Math.pow(x1-x2,2)
if (x<x2){return k*Math.pow(x-x2,2)+y2}
for (i=1;i<len-2;i++){
var x1 = points[i][0]
var x2 = points[i+1][0]
var y1 = points[i][1]
var y2 = points[i+1][1]
xNew = (x-x1)*2/(x2-x1)-1
yNew = (KhanUtil.steveCubic(xNew)+1)*(y2-y1)/2+y1
if (x>=x1 && x<x2){return yNew}
}
var x1 = points[len-2][0]
var x2 = points[len-1][0]
var y1 = points[len-2][1]
var y2 = points[len-1][1]
var k = (y2 - y1)/Math.pow(x1-x2,2)
if (x>=x1){return k*Math.pow(x-x1,2)+y1}
},
makeXList: function(){
array = [-10]
i=0
while(array[i]<10){
x = array[i]+3*KhanUtil.randRange(1,3)
if (x<10){array.push(x)}
i=i+1
}
array.push(10)
return array
},
makeYList:function(min,max,n){
excluded = [0]
array = [KhanUtil.randRangeExclude(min,max,excluded)]
excluded.push(array[0])
array.push[KhanUtil.randRangeExclude(min,max,excluded)]
excluded = [0]
for (i=1;i<n;i++){
if (array[i-2]<array[i-1]){
array.push(KhanUtil.randRangeExclude(min,array[i-1]-1,excluded))
}
else{array.push(KhanUtil.randRangeExclude(array[i-1]+1,max,excluded))}
}
return array
},
makeCoordinates: function(array1,array2){
array = []
for (i=0;i<array1.length;i++){
array.push([array1[i],array2[i]])
}
return array
},
});
I think it has to do with your while loop here:
makeXList: function(){
array = [-10]
i=0
while(array[i]<10){
x = array[i]+3*KhanUtil.randRange(1,3)
if (x<10){array.push(x)}
i=i+1
}
array.push(10)
return array
},
Note that you are always incrementing i, but not always pushing a new value onto the array. If x is larger than 10, you will increment i, but there will be no element there, and that is probably what's causing your infinite loop.
I fixed my code. The problem seems to be that in both functions I had a for loop that looked like this
for(i=0;i=10;i++)
I changed that to
for(var i=0;i=10;i++)
apparently my program was treating i as a global variable, and so my two interacting functions were both incrementing the same i. Does this make sense? it seems like a pretty lousy feature to have in a programming language. Am I missing anything here?

Categories

Resources