I run the following Excel function to calculate weekly re-payments.
CELL B4 = 15000
=(PMT(6.5%/12,60,(-B4),(0.2*B4),1))*12/52
Where 6.5% = rate, 60 = number of payments, 0.2*15000 = balloon and *12/52 is for calculating weekly repayments.
The output of the above is 57.62, however when coding it up in JS I end up with 77.11 as the result. After checking through it several times I can't seem to find where I've gone wrong.
Calculation for PMT is done as follows.
var q = Math.pow(1 + rate_per_period, number_of_payments);
return -(rate_per_period * (future_value + (q * present_value))) / ((-1 + q) * (1 + rate_per_period * (type)));
I've created a fiddle showing my PMT calculations.
Also, I am using an almost exact copy of the accepted answer in another question here on SO but mine varies slightly.
My mistake!
I was doing a negative on the PMT function instead of doing the negative on the PV (present value).
var payment = pmt(interest / 12, 60, -(present), future, beginning);
Related
The following image will help explain what I am trying to achieve...
The top line (A) is a given calculated JavaScript value, lets call this the input.
The bottom line (B) is the output, so whatever input to (A) is given (will always be within the range) if a line (like the green one shown) were to be drawn I need the value of the output.
I have tried to search for phrases like "linked range", "parallel linked values" and similar but I think half of my problem is not knowing what this kind of calulation is called.
Usually I would be able to show what I have tried but on this one I really dont have a clue where to start.
Any help greatly appreciated.
So get the percentage in A
percentage = A[value] / ( A[max] - A[min] )
Use that to figure out the value in second
result = B[max] - percentage * (B[max] - B[min])
so basic JavaScript
var aMin = 0;
var aMax = 500;
var bMin = 24;
var bMax = 55;
var aValue = 100;
var percentage = aValue / ( aMax - aMin );
var result = bMax - percentage * (bMax - bMin);
console.log(result + "%");
I'm not sure how to word the question and i'm still quite new at javascript.
So I've got a random quote generator that has each quote result as an array. I'd like to add in two items in the array which I've got so far but having one result be a random number generated eg "2 quote" but having 2 be randomised each time. The end result is for a browser based text game. So it could be "2 zombies attack" or "7 zombies attack." The code I have so far is:
var quotes = [
[x, 'Zombies attack!'],
[x, 'other creatures attack'],
['next line'],
]
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
Ideally need x(or i however it's going to work) to be the result of a random number between a set range, each differently each array.
Thank you
p.s I forgot to mention that not all the quotes require a number. Thats why I've done it as a double array.
If I understand your goal correctly, you want to have a set of similar-ish message templates, pick one of them at some point and fill it with data, correct? There's a lot of ways to tackle this problem, depending on how varying can your templates be. For a simple case in my head where you just need to prepend a number to a string I'd do something like this:
var messages = [" zombies attack",
" other creatures attack"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = numberOfMonsters + messages[messageIndex]; // construct a resulting message
document.getElementById('quote').textContent = result;
If you'd rather have more complex strings where you don't necessarily add a number (or any string) to the beginning, like ["There's X things in the distance", "X things are somewhere close"], then I'd recommend to either come up with some sort of string formatting of your own or use a library to do that for you. sprintf.js seems to be just right for that, it will let you do things like this:
var messages = ["%d zombies attack",
"A boss with %d minions attacks"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = sprintf(messages[messageIndex], numberOfMonsters) // format a final message
document.getElementById('quote').textContent = result;
EDIT: Your task is much more complex than what is described in the original question. You need to think about you code and data organization. You have to outline what is finite and can be enumerated (types of actions are finite: you can loot, fight, move, etc.), and what is arbitrary and dynamic (list of monsters and loot table are arbitrary, you have no idea what type and amount of monsters game designers will come up with). After you've defined your structure you can come up with some quick and dirty message composer, which takes arbitrary entities and puts them into finite amount of contexts, or something. Again, I'm sort of shooting in the dark here, but here's an updated version of the code on plunkr.
I solved it to do what I want and still have the numbers different. The issue was I should have had the number generator within the quote function. Also can create multiple variables to use too for different number generators. The plan is to then integrate it with php to add content dynamically. Which I can do. Thanks Dmitry for guiding me in the right direction.
function newQuote() {
var MonsterOne = Math.floor((Math.random() * 14) + 0);
var MonsterTwo = Math.floor((Math.random() * 14) + 0);
var MonsterThree = Math.floor((Math.random() * 14) + 0);
var MonsterFour = Math.floor((Math.random() * 14) + 0);
var quotes = [
['Test', MonsterOne, 'One'],
['Test', MonsterOne,'Two'],
['Test', MonsterThree, 'Three'],
[MonsterFour, 'Four'],
['Five'],
]
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
I would like to perform some calculations on an ee.Image pixel by pixel, however, the result calculated must obey a probabilistic Gaussian distribution, so some pixels will be modified and others not. I already coded a probabilistic function but I don't know how to apply it to each pixel in GEE. Is there any way to do that?
I already tried something like the following, but the same random number is used for every pixel, and that is not what I want.
Trial 1)
var result = img.where(img.lte(32 + Math.floor((Math.random() * 10) + 1)),1);
Trial 2)
var result = img.expression(
'(B1 > 32 + P) ? 1', {
'P': Math.floor((Math.random() * 10) + 1),
'B1': img.select('B1')});
Trial 3)
var result = img.expression(
'P > 10 ? 1', {
'P': MyProbabilisticFunction(),
'B1': img.select('B1')});
I also tried to use the following to generate a "probabilistic" image to perform my calculations but, since I have several classes in the same raster, the probability of the "event" is not quite right.
Trial 4)
var rd = ee.FeatureCollection.randomPoints(geometry,1000,Math.floor((Math.random() * 10) + 1));
var prob = rd.draw('000000',5,0).select('vis-red');
var result = img.where(prob.eq(0),1);
You can generate a random value per pixel using ee.Image.random().
That said, the rest of Earth Engine doesn't work the way you're attempting to use it. All image functions are "vectorized"; you don't ever get to work "pixel by pixel".
Allright, I know what machine precision is, but this, I can't understand...
Code:
console.log("meanX",meanX);
meanX2 = meanX * meanX; //squared
console.log("meanX2",meanX2);
Console output:
meanX 300.3
meanX2 28493.4400000000002
In case you are wondering, the correct value for meanX2 would be 90180.09
And this is only one of the many examples visible in the screenshot..
.toFixed(6) seems to fix this... But I have no idea why it doesn't work without it.
Edit
Ok, I don't want to post the whole program code here because in first place I'm not the only author, and second, I also wouldn't like this to be copied without our permission. But I'll gladly explain how I get this error and will post the whole method/function code here.
This code belongs, as you may have guessed from the window title, to a lane detection algorithm. We use Three.js/webgl to run some pre processing shaders on each frame of a video and then we analyze the resulting image. The method/function you see on the screenshot is a perpendicular line fitting algorithm and is part of the whole thing.
I can see the algorithm running nicely because I have the lane being drawn on top of the video, and It is well placed. Until suddenly the lane turns into an horizontal bar. This unexpected behavior happens exactly because of the phenomenon I described here, since it's from that moment that I start to see wrong math in the console.
Also, because the video and algorithm run at slightly different fps everytime, the problem doesn't always happen in the same moment of the video, and sometimes It doesn't happen at all.
Here is the code (it has some alterations because I was trying to isolate the issue):
this.perpendicularLineFit = function (points, slopeSign) {
var count = points.length;
var sumX = 0,
sumY = 0;
var sumX2 = 0,
sumY2 = 0,
sumXY = 0;
var meanX, meanY;
var i, lowp = {}, highp = {};
var B;
var slope;
var originY;
for (i = 0; i < count; i++) {
sumX += points[i].x;
sumY += points[i].y;
sumX2 += points[i].x * points[i].x;
sumY2 += points[i].y * points[i].y;
sumXY += points[i].y * points[i].x;
}
meanX = sumX / count;
meanY = sumY / count;
//If you uncoment this, problem reappears:
//var numeratorLeft = meanY * meanY;
console.log("meanX",meanX);
var meanX2 = meanX*meanX;
console.log("meanX2",meanX2);
var numerator = (sumY2 - count * (meanY * meanY)) - (sumX2 - count * meanX2);
var denominator = (count * meanX * meanY - sumXY);
B = 0.5 * (numerator / denominator);
slope = -B + slopeSign * Math.sqrt(B * B + 1);
originY = meanY - slope * meanX;
slope = isNaN(slope) ? slopeSign : slope;
originY = isNaN(originY) ? originY : originY;
lowp.y = this.lowY;
lowp.x = (this.lowY - originY) / slope;
highp.y = this.highY;
highp.x = (this.highY - originY) / slope;
return {
low: lowp,
high: highp
};
};
Now, I was trying to understand what was causing this, and the most bizarre thing is that it seems that when I place a statement of this form
var x = ... meanY * meanY ...;
before the meanX2 attribution, the issue happens. Otherwise it doesn't.
Also, I tried to catch this anomaly in the debugger but just when I enter the debugging tab, the problem disapears. And the values turn correct again.
I certainly don't believe in black magic, and I know that you are probably skeptic to this.
I would be too. But here is a link to a video showing it happening:
The video
Edit2:
I managed to reproduce this issue in another computer.. Both having ubuntu and using firefox (versions 20 and 21).
Edit3:
I'm sorry it took so much time! Here is a zip containing the issue. Just run it in any webserver. The code mentioned is in LaneDetection.js. Search for "HERE" in the file to find it.
https://docs.google.com/file/d/0B7y9wWiGlcYnYlo1S2pBelR1cHM/edit?usp=sharing
The problem might not happen in the first attempts. If that's the case refresh the page and try again. When the lines get horizontal you know it's there. As I said, I saw this problem happening in firefox versions 20 and 21 on ubuntu. In chrome it never happened.
By the way, I noticed that changing javascript.options.typeinference flag in firefox seems to stop the problem... I don't know exactly what that flag does, but maybe this optimization is not correctly implemented in firefox?
I can't say for sure that I actually have an answer but I think that I have confirmed that basilikum was correct to suggest a memory problem. Here's what I did: I took the first ten entries from your screenshot and calculated the correct answer. I then converted the correct answer and the wrong answer into the hexidecimal representation of the double-precision float. What I ended up with was the following:
292.416^2 = 85507.506 = 40F4E0381C71C71E
changed to 27583.373 = 40DAEFEB1C71C722
293.166^2 = 85946.694 = 40F4FBAB1C71C72A
changed to 27583.373 = 40DAEFEB1C71C722
295.818^2 = 87508.396 = 40F55D4658DC0876
changed to 28041.024 = 40DB62419637021F
294.500^2 = 86730.250 = 40F52CA400000000
changed to 27583.373 = 40DAEFEB1C71C722
297.000^2 = 88290.000 = 40F58E2000000000
changed to 28041.024 = 40DB62419637021F
221.750^2 = 49173.062 = 40E802A200000000
changed to 24964.000 = 40D8610000000000
300.300^2 = 90180.090 = 40F6044170A3D70A
changed to 28493.440 = 40DBD35C28F5C290
220.200^2 = 48488.040 = 40E7AD0147AE147B
changed to 25408.360 = 40D8D0170A3D70A4
300.600^2 = 90360.360 = 40F60F85C28F5C29
changed to 28493.440 = 40DBD35C28F5C290
213.000^2 = 45369.000 = 40E6272000000000
changed to 28032.326 = 40DB6014E5E0A72E
There's no persistent pattern to the change but there are a couple instances that are very telling of a memory issue. In the first two entries you can see that bytes 1, 2 and 3 were unchanged. In the 9th entry there's something even more odd. It would appear that bytes 0 - 3 were shifted left by exactly 4 bits! Upon considering the statement that the problem doesn't arise until after some time has passed and in light of these two anomalies, I'm fairly confident that you're encountering some sort of memory issue. Could it be, dare I say, a stack overflow?
Trying to create a loan calculator based on two sliders. I feel I'm nearly there but the syntax is letting me down plus one last formula.
I have two sliders, one which represents the loan amount, the other represents the loan length.
Here is a bit of the code to highlight all the calculations. I think there are errors here too.
function update() {
$amount = $("#slider1").slider("values", 100);
$interest = $amount / 100 * 15 ;
$perday = 15 ;
$apr = (($interest / $amount) / ("#slider2"/365) * 10000) / 100;
$amount2 = $amount + $interest;
$("#amount").val($amount1);
$("#amount2").val($amount2);
$("#amount3").val($interest);
}
Interest is charged at 15% of the amount borrowed.
Each day is worth 15p so in order to get my final charge.
[15% of the loan amount total]
– [0.15p per day credit]
I have developed a fiddle but its not correct, hence why I'm here.
Fiddle Here
How can I get both the sliders to work together so that if I move the top or bottom slider, it will affect the overall loan amount and Interest?
Any help will be most appreciated. I'm really struggling with this one.
I believe this is what you want - jsfiddle <- follow link
function update() {
$interest = 0.15 ;
$perday = 15 ;
$amount1 = $("#amount").val();
$dayscount = $("#days").val();
$amount2 = parseInt($amount1) + $interest * parseInt($amount1) + (parseInt($dayscount) * ($perday/100));
$("#amount2").val($amount2);
$("#amount3").val(parseFloat($amount2-$amount1).toFixed(2));
}
Fixed your update algorithm and your slider handlers
I considered that you last 2 fields (Your Loan & Interest) are the final value to be paid and the difference between the value to be paid and the value borrowed respectively. If this interpretation is not what you intended please comment.
UPDATE 1
Here I updated the jsfiddle. Beware that I don't know what the APR is, so validate that my calculation are right. I also did not use any rounding, cause I don't know if you need it like this
UPDATE 2
Updated with new formula here. I still have no idea if this is right or not
If i understood you right, you could do something like this:
function update() {
var interest = 0.15;
var sliderAmount = parseFloat($("#slider1").slider("option", "value"));
var days = parseFloat($("#slider2").slider("option", "value"));
var perday = 15 * days ;
var interestAmount = sliderAmount * interest * days;
$("#amount1").val(sliderAmount);
$("#amount2").val(sliderAmount);
$("#amount3").val(interestAmount+ perday);
}