我正在尝试对任意年份的经济衰退进行复利计算。以下 promise 函数计算可变投资组合的发展。
为清楚起见而编辑:
- const
recessions
是一个从 1 到 20 循环 recear 的数组(recseverity
是静态的) - 三元组 (
thisyear == recyear
) 每次运行在不同的年份触发,导致不同年份的portfolio
减少 50%
const chunk = ( horizon, principal, roi, recyear, recseverity ) => {
return new Promise( resolve => {
// Decimalise and create portfolio holder
let portfolio = principal
let crash = 1 - ( recseverity / 100 )
let grow = 1 + ( roi / 100 )
// Loop over the years and crash or grow
for (let thisyear = 1; thisyear < horizon +1; thisyear++) {
thisyear == recyear ? ( portfolio *= crash ) : ( portfolio *= grow )
console.log( portfolio )
}
console.log( 'last', portfolio )
// Resolve with the outcome
resolve( { year: recyear, result: portfolio } )
} )
}
const horizon = 20
const principal = 100
const roi = 7
const recseverity = 50
const yearlyadd = principal/horizon
const recessions = []
for (let year = 1; year < horizon +1; year++) {
recessions.push( { year: year, severity: recseverity } )
}
Promise.all( recessions.map( recession => chunk( horizon, principal, roi, recession.year, recession.severity ) ) )
.then( console.log.bind( console ) )
关键是一切都很完美,除了投资组合变量的最终结果是一个对我来说毫无意义的值。所有这些都返回 180.82637675169082。
我可以在 console.log 语句中看到 for 循环在循环的最后一次运行之前完美运行,它突然决定 180.82637675169082 是答案。这是不可能的。
上面的输出:
[ { year: 1, result: 180.82637675169082 },
{ year: 2, result: 180.82637675169082 },
{ year: 3, result: 180.82637675169082 },
{ year: 4, result: 180.82637675169082 },
{ year: 5, result: 180.82637675169082 },
{ year: 6, result: 180.82637675169082 },
{ year: 7, result: 180.82637675169082 },
{ year: 8, result: 180.82637675169082 },
{ year: 9, result: 180.82637675169082 },
{ year: 10, result: 180.82637675169082 },
{ year: 11, result: 180.82637675169082 },
{ year: 12, result: 180.82637675169082 },
{ year: 13, result: 180.82637675169082 },
{ year: 14, result: 180.82637675169082 },
{ year: 15, result: 180.82637675169082 },
{ year: 16, result: 180.82637675169082 },
{ year: 17, result: 180.82637675169082 },
{ year: 18, result: 180.82637675169082 },
{ year: 19, result: 180.82637675169082 },
{ year: 20, result: 180.82637675169082 } ]
查看 console.log 语句,循环的最后一次运行似乎破坏了一切。投资组合变量在最后一次运行之前一直很好,然后就变成了 180.82637675169082。
最佳答案
我的假设是错误的。
我假设在复利计算中,投资组合减半的年份很重要。
在现实世界中:我假设如果您投资 X 金额,那么明年或 10 年后是否会出现经济衰退很重要。
事实并非如此。
PBKAC.
非常感谢那些帮助我得出这个结论的人。
关于javascript - For 循环在循环内部和外部具有不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47982319/