Javascript loop calculation - javascript

Using the below script
var lvl = 0;
var HappB = 5;
var DecoX = 5;
var DecoY = 5;
while (lvl < 5) {
document.ofrm.UpgSD.value += Math.ceil((Math.exp((HappB + lvl) / ((DecoX * DecoY) * 1.8))) * 1 * 130000 * (Math.tanh((lvl + 1) / 20)) * (Math.tanh((lvl + 1) / 20)));
lvl++;
}
<form name="ofrm">
<input type="text" name="UpgSD" size="50" tabindex="1">
</form>
The result is
363147633676050952513778
The expected output is
363 + 1476 + 3367 + 6050 + 9525 + 13778 = 34559
How can I fix this?

Here's an updated code.
1. Your loop condition needs to be corrected.
2. .value is string. You can set to a variable and then attach it.
var lvl = 0;
var HappB = 5;
var DecoX = 5;
var DecoY = 5;
var number = 0;
while (lvl <= 5) {
number += Math.ceil((Math.exp((HappB + lvl) / ((DecoX * DecoY) * 1.8))) * 1 * 130000 * (Math.tanh((lvl + 1) / 20)) * (Math.tanh((lvl + 1) / 20)));
lvl++;
}
document.ofrm.UpgSD.value = number;
<form name="ofrm">
<input type="text" name="UpgSD" size="50" tabindex="1">
</form>

It looks like document.ofrm.UpgSD.value is being cast into a string (rather than a number).
var lvl = 0;
var HappB = 5;
var DecoX = 5;
var DecoY = 5;
var initialValue = parseInt(document.ofrm.UpgSD.value);
while (lvl < 5) {
initialValue += Math.ceil((Math.exp((HappB + lvl) / ((DecoX * DecoY) * 1.8))) * 1 * 130000 * (Math.tanh((lvl + 1) / 20)) * (Math.tanh((lvl + 1) / 20)));
lvl++;
}
document.ofrm.UpgSD.value = initialValue;

Related

How do I call a function inside a if...else statement?

Is it possible to call a function inside an if else in a function. I want to make a function, who use if else to call 1 function in each.
Live demo
The first js code to call the other functions:
function randomClick(number){
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
if (gamerand == 1){
loseClick();
}else{
winClick();
};
Lose function:
function loseClick(number){
var rand = Math.floor(Math.random() * (150 - 75 + 75)) + 1;
var rprand = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
var xprand = Math.floor(Math.random() * (200 - 100 + 100)) + 1;
xp = parseInt(xp) + xprand;
cookies = parseInt(cookies) + rand;
rp = parseInt(rp) + rprand;
losses = parseInt(losses) + 1;
}
Win function:
function winClick(number){
var rand = Math.floor(Math.random() * (200 - 100 + 100)) + 1;
var rprand = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
var xprand = Math.floor(Math.random() * (300 - 150 + 150)) + 1;
xp = parseInt(xp) + xprand;
cookies = parseInt(cookies) + rand;
rp = parseInt(rp) + rprand;
wins = parseInt(wins) + 1;
}
Thanks in advance.
You have a missing } for your function randomClick
function randomClick(number){
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
if (gamerand == 1){
loseClick();
}else{
winClick();
}
}//This was missing
You missed the } of else inside randomClick().
You can use ternary operator as follow:
function randomClick(number) {
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
gamerand == 1 ? loseClick() : winClick();
}
Demo: http://jsfiddle.net/tusharj/omo9yv9q/5/
You have a missing }. It should work without problems with this fix.
function randomClick(number){
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
if (gamerand == 1){
loseClick();
}else{
winClick();
// missing one bracket here
};

Mandelbrot set defined by a specific function

I'm experimenting with canvas and I'm trying to modify this piece of code, but unfortunately I don't understand some parts of it.
My question is - how to customize the above code to be defined for example by
f(z) = c^e(-z)
(the formula is taken from a book with fractal examples)?
I know that I need to change this part of code:
function computeRow(task) {
var iter = 0;
var c_i = task.i;
var max_iter = task.max_iter;
var escape = task.escape * task.escape;
task.values = [];
for (var i = 0; i < task.width; i++) {
var c_r = task.r_min + (task.r_max - task.r_min) * i / task.width;
var z_r = 0, z_i = 0;
for (iter = 0; z_r*z_r + z_i*z_i < escape && iter < max_iter; iter++) {
// z -> z^2 + c
var tmp = z_r*z_r - z_i*z_i + c_r;
z_i = 2 * z_r * z_i + c_i;
z_r = tmp;
}
if (iter == max_iter) {
iter = -1;
}
task.values.push(iter);
}
return task;
}
But can't what z_i, z_r, c_i, c_r really means and how I could bind them to the above formula.
Any help would be greatly appreciated.
Complex number have a two part: real, imaginary.
So z = a + b*i, where a is real part, and b*i is imaginary.
In provided sample for z=z^2+c, where z=z_r+z_i*i
NOTE: i*i = -1
So z^2 = (z_r+z_i*i)*(z_r+z_i*i) = z_r*z_r+2*z_r*z_i*i + z_i*i*z_i*i = z_r*z_r+2*z_r*z_i*i - z_i*z_i
now add c: z_r*z_r+2*z_r*z_i*i - z_i*z_i + c_r + c_i*i group it
z_r*z_r+2*z_r*z_i*i - z_i*z_i + c_r + c_i*i = (z_r*z_r - z_i*z_i + c_r) + (2*z_r*z_i + c_i)*i
So we get tmp var from code - is real part of new z
tmp = z_r*z_r - z_i*z_i + c_r
and imaginary part
2*z_r*z_i + c_i
Since z = z_r + z_i * i, we need assign
z_r = z_r*z_r - z_i*z_i + c_r
z_i = 2*z_r*z_i + c_i
UPDATE: for f(z) = e^z - c
first, few complex form: x = a+b*i = |x|(cos(p)+i*sin(p)) = |x|*e^(i*p)
where |x| = sqrt(a*a + b*b) and p = b/a
in our case: p=z_i/z_r, |z| = sqrt(z_r*z_r+z_i*z_i)
e^z = e^(z_r+z_i*i) = e^z_r * (e^z_i*i) = e^z_r * (cos(p)+i*sin(p)) = (e^z_r * cos(p)) + i * (e^z_r * sin(p))
subtract c:
(e^z_r * cos(p)) + i * (e^z_r * sin(p)) - c_r - c_i*i = (e^z_r * cos(p) - c_r) + i * (e^z_r * sin(p) - c_i)
so new z
z_r = (e^z_r * cos(p) - c_r) = (e^z_r * cos(z_i/z_r) - c_r)
z_i = (e^z_r * sin(p) - c_i) = (e^z_r * sin(z_i/z_r) - c_i)

How to write multidimensional array in JS in a loop?

I have the following code:
var marketReturns = [1];
var marketReturnsVol = [1];
var marketVolatility = [1];
var yearlyReturns = [];
var yearlyReturns2 = [];
for (y = 0; y < 50000; y++) {
for (x = 1; x <= 251; x++) {
do {
var rand1 = Math.random();
var rand2 = Math.random();
var x1 = 2.0 * rand1 - 1.0;
var x2 = 2.0 * rand2 - 1.0;
var w = Math.pow(x1, 2) + Math.pow(x2, 2);
} while (w === 0 || w > 1);
multiplier = Math.sqrt((-2 * Math.log(w)) / w);
var volVol = 1 + (((x2 * multiplier) / 100) * 5.98); // real ^VIX is 5.98.
marketVolatility[x] = volVol * marketVolatility[x - 1];
var y1 = 1 + (((x1 * multiplier) / 100) * 1.07); // 1.07 is the daily vol of ^GSPC
var y12 = 1 + (((x1 * multiplier) / 100) * 1.07 * marketVolatility[x]) + 0.00038; // 1.07 is the daily vol of ^GSPC
marketReturns[x] = y1 * marketReturns[x - 1];
marketReturnsVol[x] = y12 * marketReturnsVol[x - 1];
}
yearlyReturns[y] = marketReturns[251];
yearlyReturns2[y] = marketReturnsVol[251];
}
yearlyReturns.sort(function (a, b) {
return (a - b);
})
yearlyReturns2.sort(function (a, b) {
return (a - b);
})
for (x = 0; x < yearlyReturns.length; x++) {
document.write(yearlyReturns2[x] + ", ");
}
So essentially I am calculating marketReturns, which is marketReturns[x-1] * daily change. I want however to make this into subarrays where I can preserve all the individual marketReturns for each iteration of y instead of just preserving the last day like I am in yearlyReturns[y].
I thought I could do it as such:
marketReturns[y][x] = y1 * marketReturns[y][x - 1];
marketReturnsVol[y][x] = y12 * marketReturnsVol[y][x - 1];
But this doesn't work. Is there any way for me to start writing the marketReturns figures into subarrays? Thanks.
You can mimic the multidimensional array using nested array/nested object in javascript:
e.g.
var arr = [];
//Initialize a 10x10 "multidimensional" array
for(var i = 0; i < 10; i++) {
arr[i] = [];
for(var j = 0; j < 10; j++) {
arr[i][j] = 0;
}
}
//Store
arr[5][5] = 10;

Writing Variables into HTML from Javascript

I have some javascript and HTML to display the BPM values of a keyboard tap. On the HTML at the bottom, i have some script to get the value of 'simpleTempo' form JAVASCRIPT and write it into a non editable text box however want this to be plain text which I can assign styles with CSS to. If you could help me - it would be really appreciated!
---------------------------JAVSCRIPT---------------------------
// JavaScript Document/*
"use strict";
var startTime;
var beatTimes;
var xsum, xxsum, ysum, yysum, xysum;
var periodprev, aprev, bprev;
var isDone;
init();
function init() {
startTime = null;
beatTimes = [];
xsum = 0;
xxsum = 0;
ysum = 0;
yysum = 0;
xysum = 0;
isDone = false;
document.onkeydown = doBeat;
}
function doBeat() {
if (!isDone)
countBeat(new Date().getTime());
return true;
}
function countBeat(currTime) {
// Coordinates for linear regression
if (startTime == null)
startTime = currTime;
var x = beatTimes.length;
var y = currTime - startTime;
// Add beat
beatTimes.push(y);
var beatCount = beatTimes.length;
setValue("simpleBeats", beatCount);
setValue("simpleTime", floatToString(y / 1000, 3));
// Regression cumulative variables
xsum += x;
xxsum += x * x;
ysum += y;
yysum += y * y;
xysum += x * y;
var tempo = 60000 * x / y;
if (beatCount < 8 || tempo < 190)
setValue("simplePosition", Math.floor(x / 4) + " : " + x % 4);
else // Two taps per beat
setValue("simplePosition", Math.floor(x / 8) + " : " + Math.floor(x / 2) % 4 + "." + x % 2 * 5);
if (beatCount >= 2) {
// Period and tempo, simple
var period = y / x;
setValue("simpleTempo", floatToString(tempo, 2));
setValue("simplePeriod", floatToString(period, 2));
// Advanced
var xx = beatCount * xxsum - xsum * xsum;
var yy = beatCount * yysum - ysum * ysum;
var xy = beatCount * xysum - xsum * ysum;
var a = (beatCount * xysum - xsum * ysum) / xx; // Slope
var b = (ysum * xxsum - xsum * xysum) / xx; // Intercept
setValue("advancedPeriod", floatToString(a, 3));
setValue("advancedOffset", floatToString(b, 3));
setValue("advancedCorrelation", floatToString(xy * xy / (xx * yy), 9));
setValue("advancedTempo", floatToString(60000 / a, 3));
// Deviations from prediction
if (beatCount >= 3) {
setValue("simpleLastDev" , floatToString(periodprev * x - y, 1));
setValue("advancedStdDev" , floatToString(Math.sqrt(((yy - xy * xy / xx) / beatCount) / (beatCount - 2)), 3));
setValue("advancedLastDev", floatToString(aprev * x + bprev - y, 1));
}
periodprev = period;
aprev = a;
bprev = b;
}
}
function done() {
isDone = true;
setValue("simplePosition" , "");
setValue("simpleLastDev" , "");
setValue("advancedLastDev", "");
}
// d: Number of decimal places
function floatToString(x, d) {
if (x < 0)
return "-" + floatToString(-x, d);
var m = Math.pow(10, d);
var tp = Math.round(x % 1 * m);
var s = "";
for (var i = 0; i < d; i++) {
s = tp % 10 + s;
tp = Math.floor(tp / 10);
}
return Math.floor(Math.round(x * m) / m) + "." + s;
}
function setValue(elemId, val) {
document.getElementById(elemId).value = val;
}
---------------------------HTML---------------------------
<form action="#" method="get" onsubmit="return false" onreset="init()">
<input id="simpleTempo" action="#" method="get"/>
<input id="simpleBeats" readonly="readonly" type="hidden" />
<input id="simplePosition" readonly="readonly" type="hidden"/>
<input id="simpleTime" readonly="readonly" type="hidden"/>
<input id="advancedStdDev" readonly="readonly" type="hidden"/>
<input id="advancedOffset" readonly="readonly" type="hidden"/>
<input id="advancedCorrelation" readonly="readonly" type="hidden"/>
<input id="simpleLastDev" readonly="readonly" type="hidden"/>
<input id="advancedLastDev" readonly="readonly" type="hidden"/>
<input id="simplePeriod" readonly="readonly" type="hidden"/>
<input id="advancedPeriod" readonly="readonly" type="hidden"/>
<input id="simpleTempo" readonly="readonly" type="hidden"/>
<input type="reset" alt="reset" class="imgClass"/>
</form>
<script type="application/javascript" src="tap-to-measure-tempo.js"></script>
There is a similar post to this at:
Passing javascript variable to html textbox
Basically to get a JavaScript value into a html textbox you use getElementById
document.getElementById("simpleTempo").value = "some text";

financial rate function in javascript not working properly

the function given at
simple financial rate function in javascript
is not giving me same answers as excel rate function some time. It works perfectly for the problem given at http://allfinancialmatters.com/2009/11/03/how-to-use-the-rate-function-in-excel/ but for my test cases. its results are different from excel rate. this is strange behaviour. i am unable to sort this out. my test cases (with excel output) are
RATE(360,-665.3, 99000) = 0.0059
RATE(360,-958.63, 192000) =0.0036
RATE(180,-1302.96,192000) = 0.0023
RATE(360, -889.19, 192000) =0.00312
RATE(360, -1145.8, 240000) = 0.0033
my code.js is
function rate(paymentsPerYear, paymentAmount, presentValue, futureValue, dueEndOrBeginning, interest)
{
//If interest, futureValue, dueEndorBeginning was not set, set now
//if (interest == null) // not working here :D
if (isNaN(interest))
interest = 0.1;
//interest = 0.1;
if (isNaN(futureValue))
futureValue = 0;
if (isNaN(dueEndOrBeginning))
dueEndOrBeginning = 0;
var FINANCIAL_MAX_ITERATIONS = 128;//Bet accuracy with 128
var FINANCIAL_PRECISION = 0.0000001;//1.0e-8
var y, y0, y1, x0, x1 = 0, f = 0, i = 0;
var rate = interest; // initiallizing rate to our guess interest
if (Math.abs(rate) < FINANCIAL_PRECISION)
{
y = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
}
else
{
f = Math.exp(paymentsPerYear * Math.log(1 + rate));
y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
}
y0 = presentValue + paymentAmount * paymentsPerYear + futureValue;
y1 = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
// find root by Newton secant method
i = x0 = 0.0;
x1 = rate;
while ((Math.abs(y0 - y1) > FINANCIAL_PRECISION)
&& (i < FINANCIAL_MAX_ITERATIONS))
{
rate = (y1 * x0 - y0 * x1) / (y1 - y0);
x0 = x1;
x1 = rate;
if (Math.abs(rate) < FINANCIAL_PRECISION)
{
y = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
}
else
{
f = Math.exp(paymentsPerYear * Math.log(1 + rate));
y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
}
y0 = y1;
y1 = y;
++i;
}
return rate;
//return String(parseFloat(rate).toFixed(3)); // rounding it to 3 decimal places
//return parseFloat(rate).toFixed(3);
}
and my HTML file is
<head><title>JavaScript Loan Calculator</title>
<script src="code.js"></script>
</head>
<body bgcolor="white">
<form name="loandata">
<table>
<tr>
<td>1)</td>
<td>paymentsPerYear:</td>
<td><input type="text" name="paymentsPerYear" size="12"
onchange="calculate();"></td>
</tr>
<tr>
<td>2)</td>
<td>paymentAmount:</td>
<td><input type="text" name="paymentAmount" size="12"
onchange="calculate();"></td>
</tr>
<tr>
<td>3)</td>
<td>presentValue:</td>
<td><input type="text" name="presentValue" size="12"
onchange="calculate();"></td>
</tr>
<tr>
<td>4)</td>
<td>futureValue:</td>
<td><input type="text" name="futureValue" size="12"></td>
</tr>
<tr>
<td>5)</td>
<td>dueEndOrBeginning:</td>
<td><input type="text" name="dueEndOrBeginning" size="12"></td>
</tr>
<tr>
<td>6)</td>
<td>interest:</td>
<td><input type="text" name="interest" size="12"></td>
</tr>
<tr><td colspan="3">
<input type="button" value="Compute" onClick="calculate();">
</td></tr>
<tr>
<td>APR:</td>
<td><input type="text" name="APR" id="APR" size="12"></td>
</tr>
</table>
</form>
<script language="JavaScript">
function calculate() {
var paymentsPerYear = document.loandata.paymentsPerYear.value;
var paymentAmount = document.loandata.paymentAmount.value;
var presentValue = document.loandata.presentValue.value;
var futureValue = document.loandata.futureValue.value;
var dueEndOrBeginning = document.loandata.dueEndOrBeginning.value ;
var interest = document.loandata.interest.value ;
var ans = rate(parseFloat(paymentsPerYear), parseFloat(paymentAmount), parseFloat(presentValue), parseFloat(futureValue), parseFloat(dueEndOrBeginning), parseFloat(interest));
document.loandata.APR.value=ans;
//alert(futureValue);
}
</script>
</body>
</html>
In case anyone is still looking for a javascript implementation of the Excel's Rate function, this is what I came up with:
var rate = function(nper, pmt, pv, fv, type, guess) {
// Sets default values for missing parameters
fv = typeof fv !== 'undefined' ? fv : 0;
type = typeof type !== 'undefined' ? type : 0;
guess = typeof guess !== 'undefined' ? guess : 0.1;
// Sets the limits for possible guesses to any
// number between 0% and 100%
var lowLimit = 0;
var highLimit = 1;
// Defines a tolerance of up to +/- 0.00005% of pmt, to accept
// the solution as valid.
var tolerance = Math.abs(0.00000005 * pmt);
// Tries at most 40 times to find a solution within the tolerance.
for (var i = 0; i < 40; i++) {
// Resets the balance to the original pv.
var balance = pv;
// Calculates the balance at the end of the loan, based
// on loan conditions.
for (var j = 0; j < nper; j++ ) {
if (type == 0) {
// Interests applied before payment
balance = balance * (1 + guess) + pmt;
} else {
// Payments applied before insterests
balance = (balance + pmt) * (1 + guess);
}
}
// Returns the guess if balance is within tolerance. If not, adjusts
// the limits and starts with a new guess.
if (Math.abs(balance + fv) < tolerance) {
return guess;
} else if (balance + fv > 0) {
// Sets a new highLimit knowing that
// the current guess was too big.
highLimit = guess;
} else {
// Sets a new lowLimit knowing that
// the current guess was too small.
lowLimit = guess;
}
// Calculates the new guess.
guess = (highLimit + lowLimit) / 2;
}
// Returns null if no acceptable result was found after 40 tries.
return null;
};
Testing the function with Abdul's test cases give the following results:
rate(360,-665.3, 99000);
0.005916521358085446
rate(360,-958.63, 192000);
0.0036458502960158515
rate(180,-1302.96,192000);
0.0022917255526408564
rate(360, -889.19, 192000);
0.0031250616819306744
rate(360, -1145.8, 240000);
0.003333353153720964

Categories

Resources