Convert equation string to equation [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Running an equation with Javascript from a text field
How can I convert the following:
var n = "2x^3+3x+6";
To
var x = a number
var n = 2x^3+3x+6;
In JavaScript?

Quite hard to guess what the exact requirements and the context are, but if you want to roughly stick to the grammar demonstrated by your variable I'd suggest using a math expression parser.
Using js-Expression-eval, it could look like this:
var formula = "2*x^3+3*x+6";
var expression = Parser.parse(formula);
var result = expression.evaluate({ x: 3 });
Run the Fiddle
Should you want to have your own grammar - to leave out the * symbols for multiplication with variables, for example - you'll have to roll your own parser, for example using something like jison.

var x = a number;
var n = eval("2*Math.pow(x,3)+3*x+6")

Related

Excel formula calculations into JavaScript [duplicate]

This question already has answers here:
JavaScript exponents
(8 answers)
Closed 4 years ago.
I have a formula into my excel sheet, now I am making that formula using JavaScript. I made a code exact like written on excel sheet but in JavaScript I am getting different result, I mean wrong result.
Excel formula
= H4*((((1+H7)^H8-1)/H7)*(1+H7))
JavaScript
var contribute = 1000;
var cum_rate = 0.001666667;
var num_periods = 480;
var fvc = contribute * ((((1 + cum_rate) ^ num_periods - 1) / cum_rate) * (1 + cum_rate));
console.log(fvc);
Result of this calculations should be 735659.68 but here I am getting wrong result, can you guys help me out what I am doing wrong here?
The karat doesn't mean exponent. You need to use Math.pow(base, exp) to evaluate the expression correctly:
var fvc = contribute*( ((Math.pow( (1+cum_rate), num_periods ) - 1)/cum_rate)*(1+cum_rate) )

functional loop given a number instead of an array [duplicate]

This question already has answers here:
Tersest way to create an array of integers from 1..20 in JavaScript
(16 answers)
Closed 6 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
Say I have a number 18, instead of an array, in hand.
What is the best way to create a functional loop in JS given a number X instead of array of X elements?
I can do this:
[1,2,3].forEach(function(){
));
but if I have the number 3
I can do
for(var i = 0; i < 3; i++){
}
but I want that loop to be functional instead
If you have a number and you want to create a loop then you can use the number in limiter condition in the for loop.
for(var i = 0; i < number; i++)
Edit 1: you can use foreach on arrays only, in that case since you have a number already you can create a array of that length and then use the foreach on it.
var foo = new Array(number).fill(0);
foo.foreach()
Also another option is
var N = 18;
Array.apply(null, {length: N}).map(Number.call, Number)
result [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
Many more options available in this thread Create a JavaScript array containing 1...N
I don't understand why you want to do this. An equivalent to:
[1,2,3].forEach(function(){ ... ));
Is
var limit = n;
while (--limit) {( // Note: 0 is falsy
function(){ ... }
)(limit);}
Or if you really want to use an array structure, the following will do:
new Array(limit).fill(0).forEach(function(){...});
You might be interested in Myth of the Day: Functional Programmers Don't Use Loops.
Per this question, you can "functionally" iterate over a linear sequence relatively easily using:
Array.apply(null, Array(number)).map(function () {}).forEach(...)
Not sure what advantage this gives you versus a regular for-loop with an index, though it is a neat trick.

Javascript Prevent Automatic Rounding [duplicate]

This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 8 years ago.
I was wondering if there was any way to prevent javascript from automatically rounding my numbers. I made a program to calculate pi using the Gregory-Leibniz series. It only goes to a certain amount of decimal places. Here is my code:
pi=0;
x=1;
i=1;
function doStuff(){
pi = pi+(4/x);
x=x+2;
pi = pi-(4/x);
x=x+2;
document.getElementById("someDiv").innerHTML = pi;
}
If you are trying to work with numbers requiring precision beyond the JavaScript float (only 64 bits of precision) you could consider using a library like one of those mentioned in this question: Is there a decimal math library for JavaScript?
In particular the bignumber library looks promising for your purposes.
Here is a quick demonstration jsfiddle: http://jsfiddle.net/H88tS/
Note that the fiddle is linking in the bignumber library.
$(document).ready(function () {
BigNumber.config({ DECIMAL_PLACES : 50, ERRORS : false});
var pi = new BigNumber(0, 10),
x = new BigNumber(1, 10),
two = new BigNumber(2, 10),
four = new BigNumber(4, 10);
function iterate() {
pi = pi.plus(four.dividedBy(x));
x = x.plus(two);
pi = pi.minus(four.dividedBy(x));
x = x.plus(two);
$("#pi").text(pi.toPrecision(50));
}
$('button').click(iterate);
});
Unfortunately, it's computationally impossible to prevent rounding of a number with potentially infinite decimal places.
There are some hacks one could suggest, though, like having a class HugeNumber whose objects are lists or arrays of algarisms, or even strings that contain only numbers, and having arithmetic operations implemented in it (by yourself, of course). Unless processing efficiency is a concern, this would be an acceptable solution. Maybe something like that already exists in a plugin or even in some built-in class, I just never needed that so I really don't know.

How to get x of 2^x=8000? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What's the opposite of JavaScript's Math.pow?
2^x=i
Given i, how can we calculate x using Javascript?
You want to take the logarithm of 8000. JS has the Math.log function which uses base e, you want base 2 so you can write Math.log(8000) / Math.log(2) to get the logarithm of 8000 base 2, which is equal to x.
You need the logarithm from the Math object. It does not provide a base 2 log so do the conversion:
var x = Math.log(8000) / Math.log(2);
Reference to the javascript Math object.
In the more general case we calculate 2^x = i this way:
var i; // Some number
var x = Math.log(i) / Math.log(2);

Javascript mix numbers randomly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to randomize a javascript array?
Hello guys I know how to generate a random value with Math.random() in Javascript, but can you tell me how to mix numbers randomly?
For example I have numbers 1,2,3,4,5,6,7,8,9,10 how to mix it randmoly like this: 2,8,9,1... so each number should be used only once
You could do this by putting them all in an array and sort that array in a random fashion.
var nrs = [1,2,3,4,5,6,7,8,9,10];
nrs.sort(function(a,b){
return Math.floor(Math.random()*3 - 1);
});
var nums = [1,2,3,4,5,6,7,8,9,10], numsMixed = [];
while(nums.length){
numsMixed = numsMixed.concat(nums.splice((Math.random() * nums.length), 1));
}
console.log(numsMixed);

Categories