Chr*_*s T 5 c++ math equations
我被分配了一个程序来获取输入并输出一个表格来计算Verhulst公式的k年数.我用这个等式:
http://www.resnet.wm.edu/~jxshix/math410/Verhulst.html
等式如下:
p(n + 1)=(1 + gh)p(n)-gp(n)^ 2/M.
这是我制作的节目.我已经删除了我的代码请求输入的部分,因为我觉得你们筛选的过程会很乏味:
> #include <iostream>
using namespace std;
int main() {
int k = 20; // number of years to calculate for
int pn = 10; // the population of animals for the first year
double g = 275; // rate of growth
g = g/100.00;
double h = 20; // rate of animal death/animals leaving population
h = h/100.00;
int M = 100; // carrying capacity of the ecosystem
/*
Implementing Verhulst's Formula in C++
*/
int i;
int pop;
for (i = 1; i <= k ; i++)
{
pop = (((1 + (g - h)) * pn) - g*(pn*pn)/M) + .5; // the equation
pn = pop; // this takes the new value of pop and inserts it as pn, to be looped until i <= k
cout << i << " " << pop << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我被指示使用上面链接中的示例来测试我的代码,该示例将g(增长率)分别设置为125,250和300.我觉得我的程序对前两个数字非常准确(它们相当准确地匹配图形)但是当我插入300时,我得到的图表中的值非常不同.我不确定我在代码中表达上述内容时是否犯了某种错误,或者图表是否特别糟糕.我使用上述网站上提到的参数保持其他一切不变.
这是我得到的输出我设置g = 300.第一列是年,第二列是人口:
1 35
2 96
3 88
4 102
5 75
6 116
7 37
8 100
9 80
10 112
Run Code Online (Sandbox Code Playgroud)
与我在上面链接中的第3个图表中看到的输出相比.再次,这些是猜测,所以我不能保证他们的准确性:
1 25
2 70
3 120
4 33
5 94
6 90
7 98
8 86
9 92
10 70
Run Code Online (Sandbox Code Playgroud)
我可以获得与第一和第二图匹配而不是第三图的输出是非常令人困惑的.我在C++中实现的方程式是否合理?:
int i;
int pop;
for (i = 1; i <= k ; i++)
{
pop = (((1 + (g - h)) * pn) - g*(pn*pn)/M) + .5; // the equation
pn = pop; // this takes the new value of pop and inserts it as pn, to be looped until i <= k
cout << i << " " << pop << endl;
}
Run Code Online (Sandbox Code Playgroud)
请注意,第三张图中第 0 年的人口最初为 120,而不是 20。将您的输入更改为 120,您最终得到的值将更接近您查看的表格的值。
将数据保留为提供的代码中的类型,输出将变为:
1 24
2 74
3 117
4 34
5 95
6 90
7 99
8 82
9 110
10 55
11 118
12 31
13 89
14 101
15 78
16 114
17 43
18 108
19 60
20 120
Run Code Online (Sandbox Code Playgroud)
我想指出的是,如果您double对所有值都使用类型,则无需添加 0.5 来考虑舍入误差:
#include <iostream>
using namespace std;
int main() {
int k = 20; // number of years to calculate for
double pn = 120; // the population of animals for the first year
double g = 300; // rate of growth
g = g/100.00;
double h = 20; // rate of animal death/animals leaving population
h = h/100.00;
double M = 100; // carrying capacity of the ecosystem
/*
Implementing Verhulst's Formula in C++
*/
int i;
double pop;
for (i = 1; i <= k ; i++)
{
pop = (((1 + (g - h)) * pn) - g*(pn*pn)/M); // the equation
pn = pop; // this takes the new value of pop and inserts it as pn, to be looped until i <= k
cout << i << " " << (int)pop << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这将产生
1 24
2 73
3 116
4 34
5 94
6 91
7 97
8 85
9 105
10 67
11 119
12 25
13 76
14 115
15 39
16 102
17 73
18 117
19 32
20 91
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
436 次 |
| 最近记录: |