Skip to content

Instantly share code, notes, and snippets.

@actuallymentor
Created November 28, 2016 13:57
Show Gist options
  • Save actuallymentor/989dba92fbd9b3948410a41c5998f3d5 to your computer and use it in GitHub Desktop.
Save actuallymentor/989dba92fbd9b3948410a41c5998f3d5 to your computer and use it in GitHub Desktop.
Calculating the amount of money you need to set aside to reach a certain amount of wealth. Basically reversing compound interest by brute force.
// This script is terribly inefficient, but on a decent computer it takes 1 second to complete anyway. I made it on an airplane while half asleep.
const target = 600000 // The target net worth
const roi = 4 // The assumed return on investment yearly
const term = 20 // Time until retirement
const start = 0 // Starting capital
const desire = 600000 // Desired capital
// Configuration
const verbose = false
// Function to calculate the compound result of investing with the above parameters based on a monthly addition
// The monthly addition is assumed to be a yearly addition for simplicity sake
const compound = monthly => {
let result = start
let input = start
// Loop over the years
for (var i = term - 1; i >= 0; i--) {
result += monthly * 12
result *= ( 1 + ( roi / 100 ) )
input += monthly * 12
}
// Log out the results and return the resulting value
if ( verbose ) console.log( 'Monthly ' + monthly + ' totals ' + input + ' becomes ' + result )
return result
}
// Brute force the needed monthly investment based on an accuracy parameter
// The smaller the parameter the more accurate the amount, but the more expensive the calculation
const bruteForce = step => {
let calculator = desire + 1
let monthly = ( desire / term ) / 12
while ( calculator > desire ) {
calculator = compound( monthly )
monthly -= step
}
console.log( 'Monthly investment needed: ' + monthly )
}
bruteForce( 1 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment