[英]Troubles with a math formula - Java
I'm making a program for my java class that calculates the population for a year given the start year (2011) and increases the population by 1.2% every year. 我正在为我的java课程制作一个程序,用于计算开始年份(2011年)的一年人口,并且每年增加1.2%的人口。 The population for 2011 is 7.000 (I'm using decimals, instead of billions).
2011年的人口是7.000(我使用的是小数,而不是数十亿)。 I currently have this code.
我目前有这个代码。
int startYear = 2011;
int endYear = user_input.nextInt();
double t = 1.2; //Population percent increase anually
double nbr = (endYear - startYear); //Number of years increased
double pStart = 7.000; //Starting population of 2011
double pEnd = pStart * Math.exp(nbr * t); // Ending population of user input
DecimalFormat nf = new DecimalFormat("2");
System.out.println("Population in " + endYear + ": " (nf.format(pEnd)));
There's no errors in the code, everything works, but I'm having troubles with the pEnd equation. 代码中没有错误,一切正常,但我遇到了pEnd方程的麻烦。 Currently when I enter 2016 for the end year, i get 22824. I've tried googling a formula, but i can't find anything.
目前,当我在2016年进入2016年时,我得到22824.我已经尝试使用谷歌搜索公式,但我找不到任何东西。 Do any of you guys have an idea of the formula?
你们中的任何人都知道这个公式吗? If you enter 2016 for the end year, it should be around 7.433
如果您在年底输入2016,则应该是7.433左右
You're incrementing by a factor of 1.2, which would represent 120% instead of 1.2%. 你的增量是1.2倍,代表120%而不是1.2%。 I think what you want is :
我想你想要的是:
double t = 0.012;
This change gives me an exact value of 7.4328558258175175 from 2011 to 2016. 从2011年到2016年,这一变化给出了我的精确值7.4328558258175175。
EDIT : here's the code as requested by the author : 编辑:这是作者要求的代码:
public static void main(String args[]){
int startYear = 2011;
int endYear = 2016;
double t = 0.012; //Population percent increase anually
double nbr = (endYear - startYear); //Number of years increased
double pStart = 7.000; //Starting population of 2011
double pEnd = pStart * Math.exp(nbr * t); // Ending population of user input
System.out.println("Population in " + endYear + ": " + pEnd);
}
使用Math.pow(1 + t / 100, nbr)
而不是Math.exp(nbr * t)
因为你需要(1+t/100)^nbr
(即在nbr
次自身乘以1 + t / 100
),而不是exp^(nbr*t)
:
double pEnd = pStart * Math.pow(1 + t / 100, nbr); // Ending population of user input
试试这个。
double pEnd = pStart * Math.pow(1.0 + t / 100, nbr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.