我一直在尝试制作一个可以接受的程序:
然后能够计算出投资达到收支平衡所需的年数。我已经能够通过蛮力算法来做到这一点。
我想知道是否有一种方法可以更有效地做到这一点(类似于标准代数)。
我的代码:
import java.util.Scanner;
public class ReturnOnInvestment {
public static double initialValue;
public static double growthRate;
public static double purchasePrice;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Return on Investment Calculator ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.print(" Starting Value (In Billions): ");
initialValue = input.nextDouble();
System.out.print(" Growth Rate (Per Year in Billions): ");
growthRate = input.nextDouble();
System.out.print(" Purchase Price (In Billions): ");
purchasePrice = input.nextDouble();
input.close();
System.out.println("-----------------------------------------");
System.out.println(" ROI Period: " + calculateYears(0) + " Years");
}
public static double calculateMoney(double years) {
if(years < 1) return 0;
return calculateMoney(years - 1) + initialValue + (growthRate * (years - 1));
}
public static double calculateYears(double years) {
if(calculateMoney(years) >= purchasePrice) return Math.round(years * 100) / 100.0;
return calculateYears(years + 0.01);
}
}
答案 0 :(得分:0)
是-您可以为此使用对数函数。
鉴于您的Java代码,您可以编写:
public static double yearsNeeded(double initialValue, double growthRate, double purchasePrice) {
return Math.log(purchasePrice / initialValue) / Math.log(1 + growthRate);
}
以示例:
public static void main(String[] args) {
System.out.println("Years to go from 100 to 150 with a growth rate of 5%: "
+ yearsNeeded(100, .05, 150));
}
基本上,您要尝试解决“年”问题:
initialValue * (1 + growthRate) ^ years = purchasePrice
其中^表示幂。
您可以将其重写为:
(1 + growthRate) ^ years = purchasePrice / initialValue
变成:
years = [1 + growthRate] log (purchasePrice / initialValue)
其中日志的基础是“ 1 + growthRate”。而且,另一个基准的日志与任何基准中的日志除以该基准的日志相同。