extends Node2D
const CURRENT_PRINCIPAL: float = 5678.9
const INTEREST_RATE: float = 0.03
const COMPOUND_PER_YEAR: int = 1
var years_to_grow: int = 50
var target_amount: int = 7000
func _ready():
plot_years(CURRENT_PRINCIPAL,
INTEREST_RATE,
COMPOUND_PER_YEAR,
years_to_grow)
func plot_years(p: float, r: float, n: int , t: int):
for periods in range(t):
var a: float
a = compound_interest(p, r, n, periods)
if periods == 0:
print("Initial Principal: " + str(a))
else:
print("Year " + str(periods) + ": Principal is " + str(a))
if a > target_amount:
print("Desired amount reached at around " + str(a) + " after "
+ str(periods) + " years.")
break # breaksout from for-loop
func plot_years_version_two(p: float, r: float, n: int , t: int):
var periods: int = 0
while periods < t:
var a: float
a = compound_interest(p, r, n, periods)
match periods:
0:
print("Initial Principal: " + str(a))
_:
print("Year " + str(periods) + ": Principal is " + str(a))
if a > target_amount:
print("Desired amount reached at around " + str(a) + " after "
+ str(periods) + " years.")
break # breaksout from while-loop
periods += 1
func compound_interest(p: float, r: float, n: int , t: int) -> float:
return stepify(p * pow((1 + r / n), n * t), 0.01)
Output:
Initial Principal: 5678.9
Year 1: Principal is 5849.27
Year 2: Principal is 6024.75
Year 3: Principal is 6205.49
Year 4: Principal is 6391.65
Year 5: Principal is 6583.4
Year 6: Principal is 6780.9
Year 7: Principal is 6984.33
Year 8: Principal is 7193.86
Desired amount reached at around 7193.86 after 8 years.
The GDScript above combines what we have learned so far from the previous tutorials. If this is your first time on this page, please study the previous tutorials of series 1 in order to grasp the code above. You can copy the code above or download the source code here.
In this example, we solve for the compound interest every year till the desired amount is reached.
As for your practice, create a program combining most of the operators, types, functions, and etc., based on the previous tutorials.
0 comments:
Post a Comment