我有一段代码可以计算任何给定日的股价,给出漂移,波动率和随机数。但是当我检查输出列表时 - 它们是算术级数,而不是几何级数(幂函数)。我分享的变量有问题吗?
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>
#include <math.h>
#include <limits.h>
#include <string.h>
int main()
{
long double drift_year,volatility_year,volatility_day,drift_day,drift_mean,stockprice_initial,stockprice[100000],prefixsum[100000];
int i,len=0;
printf("Enter the yearly drift in percentage : "); //Drift factor of stock
scanf("%Lg",&drift_year);
printf("Enter the yearly volatility in percentage : "); //Volatility factor of stock - how much the "random shock" must affect the stock price
scanf("%Lg",&volatility_year);
printf("Enter initial stock price : $"); //Initial Stock Price
scanf("%Lg",&stockprice_initial);
FILE *myFile = fopen("RNG2.txt", "r"); //File with the random numbers I have
while (!feof(myFile))
{
long double number;
fscanf(myFile, "%Lg", &number); //Reading the random numbers from file
prefixsum[len++]=number;
}
fclose(myFile);
drift_day = drift_year/(100*252); //converting per annum drift to per day drift
volatility_day = volatility_year/(100*sqrt(252)); //similarly for volatility
drift_mean = drift_day - (0.5*pow(volatility_day,2)); //average it out
#pragma omp parallel for default(none) private(i) shared(drift_mean,volatility_day,stockprice,stockprice_initial,len,prefixsum) //parallelising code in OpenMP - check for missing variable in shared - mifght be causing error
for(i=0;i<len;i++)
{
stockprice[i] = stockprice_initial*pow(2.71828,((drift_mean*(i+1))+(volatility_day*prefixsum[i]))); //Must give me an exponential curve if volatility is 0;
}
for(i=0;i<len;i++)
{
printf("%d : %Lg\n",i,stockprice[i]);
}
FILE *fp = fopen("StockPrice.txt", "w");
for(i=0;i<len-1;i++)
{
fprintf(fp, "%Lg", stockprice[i]);
fprintf(fp, "\n");
}
fprintf(fp, "%Lg", stockprice[len-1]);
fclose(fp);
return 0;
}
随机数文件的链接是here
答案 0 :(得分:1)
在
上发出警告 drift_year
在此行中未初始化使用:
drift_day = drift_year/(100*252);