I'm trying to create a function that returns the money I have after x years of interest.
var calculateInterest = function(total, year, rate) {
(var interest = rate / 100 + 1;
return parseFloat((total * Math.pow(interest, year)).toFixed(4))
}
console.log(calculateInterest(915, 13, 2));
I'm not getting it to work and I'm stuck!
Any advice?
You were close. You don't need parentheses around var interest:
var calculateInterest = function(total, year, rate) {
var interest = rate / 100 + 1;
return parseFloat((total * Math.pow(interest, year)).toFixed(4));
}
var answer = calculateInterest(915, 13, 2);
console.log(answer);
I'd recommend cleaning it up a little to:
var calculateInterest = function(total, years, ratePercent, roundToPlaces) {
var interestRate = ((ratePercent / 100) + 1);
return (total * Math.pow(interestRate, years)).toFixed(roundToPlaces);
}
var answer = calculateInterest(915, 13, 2, 2);
console.log(answer);
You don't need parseFloat() if the variable is already a number (it's needed when you're parsing from a string, which is not the case here). I am adding a parameter to specify how many decimal places to round to is useful so you can control the output of the function.
Updated fiddle
Related
I'm trying to make a line chart like the New York Times Coronavirus Deaths by U.S. State and Country Over Time: Daily Tracker.
NYT has some clever lines in the chart showing the doubling rate, every day, every 2 days, every 3 days, every week, and so on.
I'm wondering how to write a function that returns an array of values that represent these lines given a start value of 10 and a maxX-value of 36 (total number of days as of today).
This is where I'm at right now, I'm afraid it does not calculate the values correctly but it might explain what I want to achieve.
How can I do this in a correct way? My math is too rusty for this.
var maxX = 36;
var start = 10;
function double(factor) {
var f = start;
var arr = [f];
for (var i = 1; i < maxX; i++) {
f = f + (f / factor)
arr.push(f)
}
return arr
}
var lines = [1, 2, 3, 7, 30].map(f => {
return {
days: f,
arr: double(f)
}
})
console.log(lines)
You first need to figure out what to multiply each daily value by, given a doubling rate. For example, with a doubling rate of every 2 days, you'd want each day count to be multiplied by 1.412 (square root of 2); after 1 day, it'd be 1.412x, after 2 days, it'd be 2x, after 4 days, it'd be 4x, etc.
For the general solution, the equation to solve is:
orig * (dayFactor ** daysToDouble) = 2 * orig
where orig is the original number of infections (here, 10), and dayFactor is the value you want to solve for, since that's the number the infections should be multiplied each day.
orig * (dayFactor ** daysToDouble) = 2 * orig
(dayFactor ** daysToDouble) = 2
dayFactor = 2 ** (1 / daysToDouble)
In the function, identify the dayFactor given the doubling rate, then multiply the count by that each day:
var maxX = 36;
var start = 10;
function double (daysToDouble) {
const dayFactor = 2 ** (1 / daysToDouble);
let currentInfected = start;
const arr = [currentInfected];
for (var i = 1; i < maxX; i++){
currentInfected *= dayFactor;
arr.push(currentInfected);
}
return arr;
}
var lines = [1,2,3,7,30].map(f => {
return {days: f, arr: double(f)}
});
console.log(lines[2]); // double every 3rd day
I am working on a calculator that calculates simple interest and compounding interest. All good, with the simple interest, but I can't seem to be able to solve the problem with the compounding interest, using a loop. I need a loop, because pushing the data into an array to use it in a chart later.
I have the formula from here: https://www.moneysmart.gov.au/managing-your-money/saving/compound-interest
I am using this as reference: https://www.bankrate.com/calculators/retirement/roi-calculator.aspx
The code is in work here: http://www.course0001.com/fiverr/iddqd
I have this so far(updated):
// Inputs from user:
// Initial deposit (starting balance)
// Number of years
// Interest
// Frequent Deposit amount
// Deposit and compound frequency (monthly, weekly, yearly)
// Calculations
var investedCapitalArray = [];
var simpleInterestArray = [];
var compoundInterestArray = [];
var compoundPrincipal = 0;
var years = [];
var accumulatedInvestment;
function calculate() {
years = [];
let interest = rateNumeric.getNumber() / 100; // annual interest rate
let additionalDeposit = additionalNumeric.getNumber(); // Regular deposit
let frequency = freqInput.value; // Frequency of regular deposit
let initialDeposit = initialNumeric.getNumber();
let taxRate = taxNumeric.getNumber();
// Invested captal amount first year
investedCapitalArray = [];
investedCapitalArray.push(initialDeposit + (frequency * additionalDeposit));
// simple interest first year
simpleInterestArray = [];
simpleInterestArray.push((investedCapitalArray[0] * ( (interest) / 100)) * (1 - taxRate));
// compund interest first year
compoundInterestArray = [];
let firstYearInvestment = investedCapitalArray[0]; // First deposit + regular deposits in first year
for (let i = 1 ; i < yearsInput.value ; i++) {
// Invested capital over the years (correct results)
investedCapitalArray.push( (investedCapitalArray[i-1]) +
(frequency * additionalDeposit) );
// simple interest over the years (correct results)
simpleInterestArray.push( simpleInterestArray[i-1] +
((firstYearInvestment +
((frequency) * additionalDeposit) * i ) * interest) );
// compound interest over the years (incorrect results)
compoundInterestArray.push( investedCapitalArray[i-1] *
Math.pow(1 + interest / 100, i) - initialDeposit);
years.push('Year' +i);
}
}
The issue is with the paranthesis you should use (investedCapitalArray[i - 1] + compoundInterestArray[i - 1]) * (1 + 0.07). Thanks
I think the problem is with unboxing the object. Try this:
compoundInterestArray.push( compoundInterestArray[i-1] + (parseInt(investedCapitalArray[i-1]) + parseInt(simpleInterestArray[i-1])) * ( rateNumberic.getNumber() / 100)) );
Thank you everyone for the inputs, after thoroughly researching the compounding interest topic, I wrote an algorithm that works perfectly. It's actually quite simple.
My algorithm is based on this explanation:
"What Is Compound Interest? Compound interest (or compounding interest) is interest calculated on the initial principal, which also includes all of the accumulated interest of previous periods of a deposit or loan."
Therefore it works like this in a loop:
compoundInterest += (((simpleInterestArray[i - 1] + compoundInterest) * (interest));
Full code below.
for (let i = 1; i < yearsInput.value; i++) {
// Invested capital over the years (works fine)
investedCapital = (investedCapitalArray[i - 1]) +
(frequency * additionalDeposit);
investedCapitalArray.push(investedCapital);
// imple interest over the years (works fine)
simpleInterest = simpleInterestArray[i - 1] +
((firstYearInvestment + (frequency * additionalDeposit) * i) * interest);
simpleInterestArray.push(simpleInterest);
// compound interest over the years (correct results)
compoundInterest += (((simpleInterestArray[i - 1] + compoundInterest) * (interest)));
compoundInterestArray.push(compoundInterest);
}
I'm doing some maths in javascript but I'm not getting the expected result all the time.
Here's my function - some parts have been simplified.
function updateExample($widget) {
var loan = parseInt($widget.attr("data-loan"), 10);
var term = parseInt($widget.attr("data-term"), 10);
// Get the best rate
var rateInfo = GetRateInfo(loan, term);
var annualRate = rateInfo[2];
// Calculate costs
var rate = (term === 1
? annualRate / 365 * 30
: annualRate / 12) / 100;
var pow = Math.pow(rate + 1, term);
var payment = round(rate * pow / (pow - 1) * loan, 2);
var totalRepayable = round(payment * term, 2);
var totalCostCap = round(loan * 2, 2);
var costCapped = false;
console.log(totalRepayable);
console.log(totalCostCap);
if (totalRepayable > totalCostCap) {
console.log("capped");
}
}
One of the tests that's failing is when I pass in a loan of 500 and a term of 1.
As you can see, I log 3 values to the console. The first 2 values output are:
620.00 and 1000.00
Given the values, I expect the following test to fail but it doesn't.
if (totalRepayable > totalCostCap)
if (620.00 > 1000.00)
The console log reads "capped" to prove the if statement has been entered.
I'm not a javascript expert by any means but I can't see how this is failing.
Here's the custom round function:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals).toFixed(decimals);
}
Any advice appreciated.
You don't show your round function, but I'm assuming it's using .toFixed(). The problem is you don't actually have arbitrary precision floating point numbers, so it converts to string, and
console.log("620.00" > "1000.00"); // true
The thing that tipped me off is that if you log a number like 620.00 to the console it automatically truncates it, the fact that you were seeing trailing zeros suggests it's a string.
Update
Yeah, now that you posted that it's definitely returning a string. The last part of the return value is a call to .toFixed(). Just cast the result back to a number to do the comparison.
I would like to generate wrong number randomly between other slots.
Eg: the right answer is 4, but I want to make other slots give the wrong answer between the right answer.
Can anyone gives me a clue to achieve this? Thanks you in advance!
Sorry for my bad English, If you don't get my question.
var operators = {
"signOne": [
{
sign: "+",
method: function(a,b) {return a+b}
},
{
sign: "-",
method: function(a,b) { return a-b}
}
]};
var selectedOperatorA = Math.floor(Math.random()*operators.signOne.length);
this.hiddenTotalValue = operators.signOne[selectedOperatorA].method(this.valueA, this.valueB);
here is the output of my right answer.
You can:
Build a list containing the right answer, a smaller wrong answer and a bigger wrong answer
Sort the list with a custom random function
Code:
var answer = 9 - 5,
list = [
answer,
answer - 1 - ((Math.random() * 10) | 0),
answer + 1 + ((Math.random() * 10) | 0)
];
list.sort(function(a, b) { return Math.random() - 0.5; });
console.log(list);
Example output:
[2, 8, 4]
If needed, the position of the correct answer in the list would be given by list.indexOf(answer);.
You can calculate the real answer calcAnswer() and then create a function to create random numbers that is calcOtherAnswers() less than the real answer where as long as the result < answer (4 or whatever in your case) then generate a number.
Try using Math.random(); function to generate random numbers.
HTML
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
JS
var first = Math.floor((Math.random() * 10) + 1);
var second = Math.floor((Math.random() * 10) + 1);
while( second === first ){
second = Math.floor((Math.random() * 10) + 1);
}
var third = Math.floor((Math.random() * 10) + 1);
while( third === first || third === second ){
third = Math.floor((Math.random() * 10) + 1);
}
$("#first").html(first);
$("#second").html(second);
$("#third").html(third);
I see you posted the question for javascript, and I am posting an answer assuming that language.
From the documentation at Mozilla you can choose your max and min using a function.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
put in the proper values of min and max
A simple way to do this would be having an array. You push the correct value into it, then have a loop that creates random numbers and adds them if they are not inside the array yet - until the array has the required size/length.
var operators = {
"signOne": [
{
sign: "+",
method: function(a,b) {return a+b}
},
{
sign: "-",
method: function(a,b) { return a-b}
}
]};
var selectedOperatorA = Math.floor(Math.random()*operators.signOne.length);
this.hiddenTotalValue = operators.signOne[selectedOperatorA].method(this.valueA, this.valueB);
here is the output of my right answer.
I am wondering how in javascript if i was given a number (say 10000) and then was given a percentage (say 35.8%)
how would I work out how much that is (eg 3580)
var result = (35.8 / 100) * 10000;
(Thank you jball for this change of order of operations. I didn't consider it).
This is what I would do:
// num is your number
// amount is your percentage
function per(num, amount){
return num*amount/100;
}
...
<html goes here>
...
alert(per(10000, 35.8));
Your percentage divided by 100 (to get the percentage between 0 and 1) times by the number
35.8/100*10000
Best thing is to memorize balance equation in natural way.
Amount / Whole = Percentage / 100
usually You have one variable missing, in this case it is Amount
Amount / 10000 = 35.8 / 100
then you have high school math (proportion) to multiple outer from both sides and inner from both sides.
Amount * 100 = 358 000
Amount = 3580
It works the same in all languages and on paper. JavaScript is no exception.
I use two very useful JS functions:
http://blog.bassta.bg/2013/05/rangetopercent-and-percenttorange/
function rangeToPercent(number, min, max){
return ((number - min) / (max - min));
}
and
function percentToRange(percent, min, max) {
return((max - min) * percent + min);
}
If you want to pass the % as part of your function you should use the following alternative:
<script>
function fpercentStr(quantity, percentString)
{
var percent = new Number(percentString.replace("%", ""));
return fpercent(quantity, percent);
}
function fpercent(quantity, percent)
{
return quantity * percent / 100;
}
document.write("test 1: " + fpercent(10000, 35.873))
document.write("test 2: " + fpercentStr(10000, "35.873%"))
</script>
In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:
function calculatePercent(amount, percent) {
const amountDecimals = getNumberOfDecimals(amount);
const percentDecimals = getNumberOfDecimals(percent);
const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`; // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)
return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}
function getNumberOfDecimals(number) {
const decimals = parseFloat(number).toString().split('.')[1];
if (decimals) {
return decimals.length;
}
return 0;
}
calculatePercent(20.05, 10); // 2.005
As you can see, I:
Count the number of decimals in both the amount and the percent
Convert both amount and percent to integers using exponential notation
Calculate the exponential notation needed to determine the proper end value
Calculate the end value
The usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.
It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:
function getPerc(num, percent) {
return Number(num) - ((Number(percent) / 100) * Number(num));
}
// Usage: getPerc(10000, 25);
var number = 10000;
var result = .358 * number;
Harder Way (learning purpose) :
var number = 150
var percent= 10
var result = 0
for (var index = 0; index < number; index++) {
const calculate = index / number * 100
if (calculate == percent) result += index
}
return result