问题描述
我必须使用复利方程计算出我的输入之一变为三倍所花费的时间。用户必须输入预期的年收益率和初始股票价格,并且该代码应该吐出将初始股票价格增加三倍的年数(四舍五入为整数)。但是,使用我编写的代码,它什么也没给我,而且我也不知道该怎么办。
我的代码:
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
Stock_Ticker = input("Enter the stock ticker: ")
EAR = float(input("Enter Expected Annual Return: "))
ISP = float(input("Enter initial stock price: "))
expr = ISP * (1+EAR)**x
solve(ISP *(1+EAR)**x,x)
sol = solve(ISP *(1+EAR)**x,x)
print ("The price of",Stock_Ticker,"tripled after",sol,"years")
我的输出是:
The price of (Stock_Ticker) tripled after [] years
解决方法
问题
- 表达式
sol = solve(ISP *(1+EAR)**x,x)
永远不会为零。 - 您希望
sol = solve(ISP *(1+EAR)**x,x) - 3*ISP
在值变为3 * ISP时变为零
代码
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
Stock_Ticker = input("Enter the stock ticker: ")
EAR = float(input("Enter Expected Annual Return: "))
ISP = float(input("Enter initial stock price: "))
expr = ISP * (1+EAR)**x - 3*ISP # subtract 3*initial price since we want to find when expression becomes zero
sol = solve(expr,x) # Find root (zero) of expression expr
print ("The price of",Stock_Ticker,"tripled after",sol,"years")
测试运行
Enter the stock ticker: xxxx
Enter Expected Annual Return: .1
Enter initial stock price: 1
The price of xxxx tripled after [11.5267046072476] years