I want to find the inverse of a matrix with javascript; how can i do that??
I already tried downloading the mathjs library but i dont know how to initiate it
The website has a starting example, reproduced below.
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="math.js | basic usage">
<title>math.js | basic usage</title>
<script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>
</head>
<body>
<script>
// basic usage of math.js
//
// website: http://mathjs.org
// docs: http://mathjs.org/docs
// examples: http://mathjs.org/examples
// functions and constants
print(math.round(math.e, 3)); // 2.718
print(math.atan2(3, -3) / math.pi); // 0.75
print(math.log(10000, 10)); // 4
print(math.sqrt(-4)); // 2i
print(math.pow([[-1, 2], [3, 1]], 2)); // [[7, 0], [0, 7]]
print(math.derivative('x^2 + x', 'x')); // 2 * x + 1
// expressions
print(math.evaluate('12 / (2.3 + 0.7)')); // 4
print(math.evaluate('12.7 cm to inch')); // 5 inch
print(math.evaluate('9 / 3 + 2i')); // 3 + 2i
print(math.evaluate('det([-1, 2; 3, 1])')); // -7
// chaining
var a = math.chain(3)
.add(4)
.multiply(2)
.done();
print(a); // 14
// helper function to output formatted results.
function print(value) {
var precision = 14;
document.write(math.format(value, precision) + '<br>');
}
</script>
</body>
</html>
Related
I'm learning to work with recursion and so far it went well with basic examples. However I want to calculate the factorial, but I don't understand what happened step-by-step. If I do it imperatively I understand it but I fail on this example:
return x * fac(x-1); gives me back 5 * 4, so far soo good, but what happens now? Does it mean it become 20 now? So my next iteration would be then 20 * 19?
const fac = (x) => {
if(x <= 1) {
return x;
}
return x * fac(x-1);
};
console.log(fac(5)); // 120
just walk through the logic.
1. fac(5) yields 5 * fac(4)
2. fac(4) yields 4 * fac(3)
3. fac(3) yields 3 * fac(2)
4. fac(2) yields 2 * fac(1)
5. fac(1) yields 1
substituting from bottom to top, you get
fac(5) = 5 * 4 * 3 * 2 * 1
I think i understand that part now and the difference between 4 and fac(4). The steps look like:
5. 5 * // ()
4. 4 * // (20)
3. 3 * // (60)
2. 2 * // (120)
1. 1 * // (120)
However, I have another example which i cant resolve step by step, while i can see the logic in the imperatively programming.
let fibo = (x) => {
if(x<=2) {return 1;}
return fibo(x-1) + fibo(x-2);
};
console.log(fibo(4)); //3
I cant resolve step by step what return fibo(x-1) + fibo(x-2); values this gives me each step. On the imperatively programming it is
function fibonacci(num){
var a = 1, b = 0, temp;
while (num >= 1){
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
console.log(fibonacci(4); // 3
where the steps would be like
4. b = 1
3. b = 1
2. b = 2
1. b = 3
I read both articles on Big O for Recursive Fibonacci sequence but still do not have a conceptual understanding of why it is O(2^n).
This is not a duplicate of this link. Please don't mark as a duplicate. I'm looking for a conceptual answer.
This is one of the simplest recursive functions out there and I want to understand how to look at it and determine the the Big O without complex math and proofs.
// O(2^n)
function fiboR(n){
if( n === 0 || n === 1 ){
return n;
} else if ( n >=2 ){
return fiboR(n-1) + fiboR(n-2);
}
}
For example Big O for the iterative version is O(n). I can just look and see that as n increases the while loop iterations increase linearly. No complex math or long proofs needed.
// O(n)
function fibo(n){
let prev0 = 0;
let prev1 = 1;
if( n === 0 || n === 1 ){
return n;
}
while( n-- >= 2){
sum = prev0 + prev1;
prev0 = prev1;
prev1 = sum;
}
return sum;
}
It is simple to calculate by diagraming function calls. Simply add the function calls for each value of n and look at how the number grows.
The Big O is O(Z^n) where Z is the golden ratio or about 1.62.
Both the lenoardo numbers and the fibonacci numbers aproach this ratio as we increase n.
2 (2 -> 1, 0)
4 (3 -> 2, 1) (2 -> 1, 0)
8 (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
14 (5 -> 4, 3) (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
(3 -> 2, 1) (2 -> 1, 0)
22 (6 -> 5, 4)
(5 -> 4, 3) (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
(3 -> 2, 1) (2 -> 1, 0)
(4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
A good number of naive recursive functions have exponential complexity, so this is good intuition to keep in mind.
Consider this function:
function fiboR1(n){
if( n === 0 || n === 1 ){
return n;
} else if ( n >=2 ){
return fiboR1(n-1) + fiboR1(n-1);
}
}
Okay, so fiboR1 doesn't actually compute the Fibonacci sequence. That doesn't matter. Notice that its asymptotic complexity will be at least that of fiboR. This is because the two recursive calls to fiboR1(n-1) are more expensive than one call to fiboR(n-1) and one call to fiboR(n-2). So let's think about what the complexity of fiboR1 is.
Let's consider an example call to fiboR1(100).
fiboR1(100) = 2 * fiboR1(99)
= 4 * fiboR1(98)
= 8 * fiboR1(97)
= 16 * fiboR1(96)
= 32 * fiboR1(95)
= 64 * fiboR1(94)
...
See the pattern now? We have O(2^n) recursive calls to fiboR1, and each call is a constant time branch. So fiboR1 is O(2^n), which means that by extension, fiboR is also O(2^n), as big-O is an upper-bound function.
If you know the closed form for the Fibonacci sequence, we can also just do this example for fiboR directly. Let's consider fiboR(100):
fiboR(100) = fiboR(99) + fiboR(98)
= 2 * fiboR(98) + fiboR(97)
= 3 * fiboR(97) + 2 * fiboR(96)
= 5 * fiboR(96) + 3 * fiboR(95)
= 8 * fiboR(95) + 5 * fiboR(94)
= 13 * fiboR(94) + 8 * fiboR(93)
...
The number of recursive function calls follows the Fibonacci sequence. The closed form for the Fibonacci sequence is exponential in n. In fact, it is O(((1+sqrt{5})/2)^n), which is about O(1.6^n).
Assuming you accept that the function is correct, i.e. that it does calculate the Fibonacci numbers, then it is very easy to show that its running time must be exponential: it only returns 0 or 1 in the base case, and it only produces larger results by adding smaller results together.
Since the Fibonacci numbers grow exponentially, the only way you could make them by adding a lot of 1s together is by adding exponentially many 1s. Each result only gets added to the final total once, so the base case must be executed exponentially many times to produce all of those 1s as different results.
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
I want to add a random modifier to this code, something that will either add to or subtract from the damage based off of a range of +-20% of the base value. The damage would randomize between a range of 80% of result to 120% of result. For a numeric example:
attacker.Strength(20) - defender.Defense(10) = result
20 - 10 = range(8 to 12)
var Fight = function (attacker, defender) {
var result;
result = (attacker.Strength - defender.Defense);
defender.HP = defender.HP - result;
if(defender.HP >= 1) {
return defender.Name + " has taken " + result + " damage!";
} else {
return defender.Name + " has been slain";
}
};
Math.random returns a number between zero and one. Map this to your range from 0.8 to 1.2 with this:
var factor = Math.random() * 0.4 + 0.8;
// | | |
// [0, 1[ | |
// \ / |
// [0, 0.4[ /
// \ /
// [0.8, 1,2[
var result = Math.round((attacker.Strength - defender.Defense) * factor);
Not sure whether you want to round somewhere so that your player's health points are always natural numbers. If not, you should change your death condition to defender.HP > 0.
As in Math.random() * 0.4?
result = (attacker.Strength - defender.Defense) * (0.8 + Math.random() * 0.4);
For eaxact +/- 20%, use random to generate two numbers only i.e. 0, 1.
If 0, treat it as + and if 1, treat it as - e.g. below:
var randomNum = Math.round(Math.random()); //it will return 0 or 1
if(randomNum ==0){
//write +20% code here
result = (attacker.Strength - defender.Defense)*1.2;
}else{
//write -20% code here
result = (attacker.Strength - defender.Defense)*0.8;
}
EDIT: For range based, its much simpler.
var factor = 0.8 + Math.random()*0.4;
result = (attacker.Strength - defender.Defense)*factor ;
I'm learning JavaScript, and one of the exercises was to write a power function. I should also learn math because this will surely sound stupid.
I know intuitively that $2 ^ 4 = 16$ since $2 * 2 * 2 * 2 = 16$. But reading through the function, it appears that it should return 12, not 16.
If we plug the numbers in, it should look like this: $$2 * (2 * (4 - 1)) = 12$$
var power = function( base, exponent ) {
if ( exponent === 0 ) return 1;
return base * power( base, exponent - 1 );
};
power(2,4);
===> 16
Obviously I must be reading the function wrong. But how?
Your function is correctly written and you could start by analyzing the result of the function as the recursion advances and the exponent decreases.
Parameters: 2, 4. Result: 2 * power (2, 3) = 2 * 8 = 16.
Parameters: 2, 3. Result: 2 * power (2, 2) = 2 * 4 = 8.
Parameters: 2, 2. Result: 2 * power (2, 1) = 2 * 2 = 4.
Parameters: 2, 1. Result: 2 * power (2, 0) = 2 * 1 = 1.
Parameters: 2, 0. Result: 1.
Hope that was helpful.
This recursively returns 16. If $function$ is represented by $f$:
f(2, 4)=2*f(2, 3)=\dots=2*2*2*2*f(2, 0)=2*2*2*2*1=16
More generally,
f(a, b)=a*...*a*1 <- n times.
It might help to consider how the function behaves, beginning from the end.
So when the exponent equals $0$ it will return $1$, this will be taken times the base, and all of this will again be multiplied by the base, and so on, so:
$$
(((2^0*2)*2)*2)\ldots)*2
$$
The key is recursion.
power(2,4)
= 2 * power(2,3)
= 2 * (2 * power(2,2))
= 2 * (2 * (2 * power(2,1)))
= 2 * (2 * (2 * (2)))
= 16
power calls itself with a smaller exponent, which calls itself etc until the exponent is 1, for which the answer is just the base.