I can't get eval() to work with my javascript calculation - javascript

I am working on a javascript code which calculates the value of Pi. So here's the problem. When eval() calculates the string which is generated by the code it returns 1. It is supposed to return 1.49138888889 (which is a rough value of Pi^2/6).
Here's the code. It returns the correct calculation as a string, But eval() doesn't calculate it properly.
function calculate() {
var times = 10;
var functionpart1 = "1/";
var functionpart2 = "^2+";
var x;
for (var functionpistring = "", x = 1; times != 0; times--, x++) {
functionpistring = functionpistring + functionpart1 + x.toString() + functionpart2;
}
document.getElementById("value").innerHTML = eval(functionpistring.slice(0, functionpistring.length - 1));
}

function calculate() {
var times = 20, // max loops
x, // counter
f = 0, // value representation
s = ''; // string representation
function square(x) {
return x * x;
}
function inv(x) {
return 1 / x;
}
function squareS(x) {
return x + '²';
}
function invS(x) {
return '1 / ' + x;
}
for (x = 0; x < times; x++) {
f += square(inv(x));
s += (s.length ? ' + ' : '') + squareS(invS(x));
document.write(f + ' = ' + s);
}
}
calculate();

Related

Trigonometric Interpolation returns NaN

I'm a musician, who's new to programming. I use JavaScript inside Max Msp (hence the bang() and post() functions) to create a trigonometric interpolation, interpolating between given equidistant points (for testing, only values of sine from [0, 2π) and returning values from the same points). When I run the code, it returns NaN, except for x = 0, as my tau() function returns only 1 in this special case. Could it be, that it has something to do with summing Math.sin results?
var f = new Array(9);
var TWO_PI = 2*Math.PI;
bang();
function bang() {
for(var i = 0; i < f.length; i++) {
f[i] = Math.sin(i/f.length*TWO_PI);
//post("f[" + i + "]: " + Math.round(f[i]*1000)/1000 + "\n");
}
var points = new Array(f.length);
for(var i = 0; i < points.length; i++) {
var idx = i/points.length*TWO_PI;
points[i] = [i, p(idx)];
//post("p[" + points[i][0] + "]: " + Math.round(points[i][1]*1000)/1000 + "\n");
}
console.log("p(2): " + p(2/points.length*TWO_PI) + "\n");
}
function p(x) {
var result = 0;
for(var k = 0; k < f.length; k++) {
result += f[k]*tau(k, x);
}
return result;
}
function tau(k, x) {
var dividend = sinc(1/2*f.length*(x-k/f.length*TWO_PI));
var divisor = sinc(1/2*(x-k/f.length*TWO_PI));
var result = dividend/divisor;
if(f.length%2 == 0) result *= Math.cos(1/2*(x-k/f.length*TWO_PI));
if(x == 0) return 1;
return result;
}
function sinc(x) {
return Math.sin(x)/x;
}
In your tau function, if x equals k / f.length * TWO_PI (which it will since x is multiples of 1 / points.length * TWO_PI) your sinc function divides by 0, making divisor equal to NaN, which then propagates.
You have to be a bit careful in implementing sinc to avoid dividing by 0. One way is to say that if x is small enough we can replace sin(x) by the first few terms of its taylor series, and all the terms are divisible by x.
I don't know javascript but here is the function in C in case it is of use
#define SINC_EPS (1e-6)
// for small x,
// missing sinc terms start with pow(x,4)/120, and value close to 1
// so the error too small to be seen in a double
double sinc( double x)
{ if ( fabs(x) < SINC_EPS)
{ return 1.0 - x*x/6.0;
}
else
{ return sin(x)/x;
}
}

A non-repeating pseudo random number generator in JavaScript

I want to generate 6-digit numeric coupon codes in JavaScript.
I'd like to use something like Preshing's algorithm.
This is what I have so far,
const p = 1000003;
function permuteQPR(x) {
const residue = x * x % p;
return (x <= p/2) ? residue : p - residue;
}
function next() {
return permuteQPR(
(permuteQPR(m_index++) + m_intermediateOffset) ^ 0x5bf03635
);
};
const seedBase = 123456;
const seedOffset = 44;
m_index = permuteQPR(permuteQPR(seedBase) + 0x682f0161);
m_intermediateOffset = permuteQPR(
permuteQPR(seedOffset) + 0x46790905
);
for (i = 0; i < 20; i++) {
document.body.innerHTML += ('000000' + next()).substr(-6) + "<br>";
}
There is also a jsfiddle.
This one works and is unique:
const p = 1000003;
const seed1 = 123456;
const seed2 = 123457;
function calculateResidue(x) {
const residue = x * x % p;
return (x <= p/2) ? residue : p - residue;
}
function valueForIndex(index) {
const first = calculateResidue((index + seed1) % p);
return result = calculateResidue((first + seed2) % p);
};
let codes = [];
for(i=0;i<1000000;i++) {
const code = valueForIndex(i);
if(codes.indexOf(code)==-1) codes.push(code);
};
document.body.innerHTML += "Unique codes: " + codes.length;

Trying to write a javascript function that counts to the number inputted

Trying to take an integer and have it return as a
string with the integers from 1 to the number passed.
Trying to use a loop to return the string but not sure how!
Example of how I want it to look:
count(5) => 1, 2, 3, 4, 5
count(3) => 1, 2, 3
Not really sure where to even start
I would do it with a recursive function. Keep concatenating the numbers until it reaches 1.
var sequence = function(num){
if(num === 1) return '1';
return sequence(num - 1) + ', ' + num;
}
Or just:
var sequence = (num) => num === 1 ? '1' : sequence(num - 1) + ', ' + num;
You can use a for loop to iterate the number of times that you pass in. Then, you need an if-statement to handle the comma (since you don't want a comma at the end of the string).
function count(num) {
var s = "";
for(var i = 1; i <= num; i++) {
s += i;
if (i < (num)) {
s += ', ';
}
}
return s;
}
JSBin
Try this:
function count(n) {
var arr = [];
for (var i = 1; i<=n; i++) {
arr.push(i.toString());
}
return arr.toString();
}
Here's a non-recursive solution:
var sequence = num => new Array(num).fill(0).map((e, i) => i + 1).toString();
here is a goofy way to do it
function count(i)
{
while (i--) {
out = (i + 1) + "," + this.out;
}
return (out + ((delete out) && "")).replace(",undefined", "");
}
Quite possibly the most ridiculous way, defining an iterator:
"use strict";
function count ( i ) {
let n = 0;
let I = {};
I[Symbol.iterator] = function() {
return { next: function() { return (n > i) ? {done:true}
: {done:false, value:n++} } } };
let s = "";
let c = "";
for ( let i of I ) {
s += c + i;
c = ", "
}
return s;
}
let s = count(3);
console.log(s);

Javascript autoincrement index

I need to create a function or use if is possible an already made library to auto increment an index. For example if it starts with 'A' it has to be incremented to 'Z' and after 'Z' it has to start from 'A1' and as soon as . . .'B1','C1', ... 'Z1', 'A2','B2',... . Does exist something like this already made ?
My idea is this, but start from 'A' and don't add number . . .
function nextChar(cont,letter) {
if (cont === 0){return letter;}
else {
letter=letter.charCodeAt(0) + 1;
return String.fromCharCode(letter);
}
}
One of many options:
function nextIndex(idx) {
var m = idx.match(/^([A-Z])(\d*)$/)
if(!m)
return 'A';
if(m[1] == 'Z')
return 'A' + (Number(m[2] || 0) + 1);
return String.fromCharCode(m[1].charCodeAt(0) + 1) + m[2];
}
var a = "";
for(i = 0; i < 100; i++) {
a = nextIndex(a)
document.write(a + ", ")
}
This one's less efficient than georg's but maybe easier to understand at first glance:
for (var count = 0, countlen = 5; count < countlen; count++) {
for (var i = 65, l = i + 26; i < l; i++) {
console.log(String.fromCharCode(i) + (count !== 0 ? count : ''));
}
}
DEMO
Allow me to propose a solution more object-oriented:
function Index(start_with) {
this.reset = function(reset_to) {
reset_to = reset_to || 'A';
this.i = reset_to.length > 1 ? reset_to[1] : 0; // needs more input checking
this.c = reset_to[0].toUpperCase(); // needs more input checking
return this;
};
this.inc = function(steps) {
steps = steps || 1;
while(steps--) {
if (this.c === 'Z') {
this.i++;
this.c = 'A';
} else {
this.c = String.fromCharCode(this.c.charCodeAt(0) + 1);
}
}
return this;
};
this.toString = function() {
if (this.i === 0) return this.c;
return this.c + '' + this.i;
};
this.reset(start_with);
}
var a = new Index(); // A
console.log('a = ' + a.inc(24).inc().inc()); // Y, Z, A1
var b = new Index('B8'); // B8
console.log('a = ' + a.reset('Y').inc()); // Y, Z
console.log('b = ' + b); // B8
Another way to think about this is that your "A1" index is just the custom rendering of an integer: 0='A',1='B',26='A1',etc.
So you can also overload the Number object to render your index. The big bonus is that all the math operations still work since your are always dealing with numbers:
Number.prototype.asIndex = function() {
var n = this;
var i = Math.floor(n / 26);
var c = String.fromCharCode('A'.charCodeAt(0) + n % 26);
return '' + c + (i ? i : '');
}
Number.parseIndex = function(index) {
var m;
if (!index) return 0;
m = index.toUpperCase().match(/^([A-Z])(\d*)$/);
if (!m || !m[1]) return 0;
return Number((m[1].charCodeAt(0) - 'A'.charCodeAt(0)) + 26 * (m[2] ? m[2] : 0));
};
var c = 52;
var ic = c.asIndex();
var nc = Number.parseIndex(ic);
console.log(c+' = '+ic+' = '+nc); // 52 = A2 = 52
If you go this way I would try to check if the new methods don't already exist first...

Javascript: getting rid of nested loop

It's been a while since I wrote any Javascript. Is there a more elegant way to do this. Specifically want to get rid of the second loop:
<script>
var number = 0;
for (var i=1; i<11; i++) {
for (var x=1; x<11; x++) {
if (i==1) {
number = x;
} else {
number = Math.pow(i, x);
}
document.write(number + " ");
if (x == 10) {
document.write("<br>");
}
}
}
</script>
I would stick with 2 loops but i would change one if statement and move it after the 2nd loop and avoid document.write and insert it all at once to reduce the number of time you change the DOM
let result = ''
for (let i = 1; i < 11; i++) {
for (let x = 1; x < 11; x++)
result += (i==1 ? x : Math.pow(i, x)) + ' '
result += '<br>'
}
document.body.insertAdjacentHTML('beforeend', result)
Edit If you really don't want the 2nd loop:
let result = ''
// you must swap the condition to check for x instead of i
for (let i = 1, x = 1; x < 11; i++) {
result += (x==1 ? i : Math.pow(x, i)) + ' '
// and reset i and increase x yourself
if (i == 10) {
i = 0
x++
result += '<br>'
}
}
document.body.insertAdjacentHTML('beforeend', result)
Edit2 just for the fun: No for loops.
Just a recursive function :P
function build(i = 1, x = 1, res = '') {
res += (x == 1 ? i : Math.pow(x, i)) + ' '
i == 10 ? (x++, i=1, res += '<br>') : i++
return x == 11 ? res : build(i, x, res)
}
document.body.insertAdjacentHTML('beforeend', build())
In terms of 'elegancy', I'd go for for... in loops or map function. That doesn't solve your nested loop though.
On a side note, nested loops are not necessarily bad. If that's the correct way to implement the specific algorithm, then that's how it is.
Using Math.pow() is un-necessary overhead. Nested loops are not necessarily bad.
var number = 0;
for (var i=1; i<11; i++) {
document.write(i + " ");
number = i;
for (var x=2; x<11; x++) {
number = (i == 1) ? x : number * i;
document.write(number + " ");
}
document.write("<br>");
}
Another way of doing it with 1 loop only, tho not as clean:
var number = 0;
var x = 1;
var calc = 0;
var calcx = 1;
var increment = false;
for (var i=1; i<101; i++) {
increment = false;
calc = i % 10;
if(calc == 0){
calc = 10;
increment = true;
}
if (calcx==1) {
number = calc;
} else {
number = Math.pow(calcx, calc);
console.log(calcx+" "+calc);
}
document.write(number + " ");
if (i % 10 == 0) {
document.write("<br>");
}
if(increment){
calcx++;
}
}
Here's another way with only one loop:
[...Array(100)].map((_,i) => {
document.write(((i>9)?Math.pow(Math.floor((i+10)/10),(i%10)+1):i+1) + ' ' + ((i%10==9)?'<br>':''));
});

Categories

Resources