There is a fully working Dijkstra algorithm that takes values from a file (or writes a new one) and writes data to a matrix. How can you improve the program using OpenMP so that its speed is significantly increased? New to openMP, had little experience with common matrices, mostly parallelization "for".
I attach all the code below:
#include <iostream>
#include <fstream>
#include <string>
#include <climits>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
#include <locale.h>
#include <chrono>
using namespace std;
class Timer
{
private:
using clock_t = std::chrono::high_resolution_clock;
using second_t = std::chrono::duration<double, std::ratio<1> >;
chrono::time_point<clock_t> m_beg;
public:
Timer() : m_beg(clock_t::now())
{
}
double elapsed() const
{
return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count();
}
};
void fillingArray(int** arr, int c, string filename) {
ofstream fout(filename);
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < c; i++){
for (int j = 0; j < c; j++) {
arr[i][j] = arr[j][i] = rand() % 10 + 1;
}
}
for (int i = 0; i < c; i++) {
fout << endl;
for (int j = 0; j < c; j++) {
fout << setw(5) << arr[i][j];
}
}
}
void read(int** arr, int c, string filename) {
char answer;
ifstream file;
file.open(filename);
if (!file) {
fillingArray(arr, c, filename);
}
else {
cout << "File found\nWant to overwrite it? (y / n)\n";
cin >> answer;
if (answer == 'y' || answer == 'Y') {
fillingArray(arr, c, filename);
}
else {
for (int i = 0; i < c; i++) {
for (int j = 0; j < c; j++) {
file >> arr[i][j];
}
}
}
}
file.close();
}
void Dijkstra(int** arr, int c, int st)
{
Timer t;
int count, index, i, u, m = st + 1;
int* distance = (int*)malloc(c * sizeof(int*));
bool* visited = new bool[c];
for (i = 0; i < c; i++)
{
distance[i] = INT_MAX; visited[i] = false;
}
distance[st] = 0;
for (count = 0; count < c - 1; count++)
{
int min = INT_MAX;
for (i = 0; i < c; i++)
if (!visited[i] && distance[i] <= min)
{
min = distance[i]; index = i;
}
u = index;
visited[u] = true;
for (i = 0; i < c; i++)
if (!visited[i] && arr[u][i] && distance[u] != INT_MAX &&
distance[u] + arr[u][i] < distance[i])
distance[i] = distance[u] + arr[u][i];
}
double time = t.elapsed();
cout << "Cost of the path from the initial peak to the rest:\t\n";
for (i = 0; i < c; i++) if (distance[i] != INT_MAX)
cout << m << " > " << i + 1 << " = " << distance[i] << endl;
else cout << m << " > " << i + 1 << " = " << "route not available" << endl;
cout << "Time passed: " << time << "с\n";
delete[] visited;
delete[] distance;
}
int main()
{
string filename, rash;
filename = "arr";
rash = ".dat";
int c;
cout << "Enter the number of ribs:\n";
cin >> c;
int** arr = (int**)malloc(c * sizeof(int*));
for (int i = 0; i < c; i++) {
arr[i] = (int*)malloc(c * sizeof(int));
}
filename += to_string(c) + rash;
read(arr, c, filename);
Dijkstra(arr, c, 0);
delete[] arr;
}
Related
i have assigment to create c++ program which will multiple 2 uknown size matrix using fork and shared memory, I have write this code but at the end for multiplication result i get all zeros. Sorry for mess code im new in this.
`
`#include<iostream>
#include<math.h>
#include<vector>
#include<signal.h>
#include<unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include<sys/wait.h>
using namespace std;
int l, m, n, job_numb;
key_t id_shared_mem;
int **B, **C, **A;
int **generateMatrix(int **matrix, int iterator, int vel){
for (int i = 0; i < iterator; i++)
{
matrix[i] = new int[vel];
for (int j = 0; j < vel; j++)
{
matrix[i][j] = (rand() % 9);
}
}
return matrix;
}
int **generateMatrixC(int **matrix, int iterator, int vel)
{
for (int i = 0; i < iterator; i++)
{
matrix[i] = new int[vel];
}
return matrix;
}
void *writeMatrixResult(int **matrix, int stupac, int red)
{
for (int i = 0; i < stupac; i++)
{
for (int j = 0; j < red; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
return NULL;
}
void write()
{
cout << "Mnozenik = " << endl;
writeMatrixResult(A, l, m);
cout << "Mnozitelj = " << endl;
writeMatrixResult(B, m, l);
cout << "Umnozak = " << endl;
writeMatrixResult(C, l, l);
}
void abort(int sig) {
if (sig == SIGINT) {
for (int i = 0; i < job_numb; i++) wait(NULL);
shmdt(A);
shmdt(B);
shmctl(id_shared_mem, IPC_RMID, NULL);
} else {
write();
shmdt(A);
shmdt(B);
shmctl(id_shared_mem, IPC_RMID, NULL);
}
exit(0);
}
void proces(int procesId)
{
while (job_numb > procesId)
{
int i = 0;
while (i < l)
{
int j = 0;
C[procesId][i] = 0;
while (m > j)
{
C[procesId][i] = C[procesId][i] + A[procesId][j] * B[j][i];
j++;
}
i++;
}
procesId++;
}
}
int main(int argc, char ** argv) {
if (argc != 4) {
cout << " unesite 3 argumenta!" << endl;
return 0;
}
l = atoi(argv[1]);
m = atoi(argv[2]);
n = atoi(argv[3]);
job_numb = l / n;
if (l % n) {
job_numb++;
}
id_shared_mem = shmget(IPC_PRIVATE, sizeof(int) * 10, 0600);
sigset(SIGINT, abort);
A = (int **)shmat(id_shared_mem, NULL, 0);
B = A + l;
C = B + l * m*m;
A = new int *[l];
B = new int *[m];
C = new int *[l];
srand(time(NULL));
A = generateMatrix(A,l, m );
B = generateMatrix(B,m,l);
C = generateMatrixC(C,l,l);
for (int i = 0; i < n; i++)
{
switch (fork()) {
case 0: { //dijete
proces(i);
exit(0);
}
case -1: { //greska
cout << "Fatalna pogreska!" << endl;
exit(1);
}
}
}
for (int i = 0; i < job_numb; i++) wait(NULL);
abort(0);
}`
`
i have try to assign only one value to matrix C like c[1][1] = 2 in proces function to see if it will write any, but still im getting all zeros on printl.
My code works fine when the file Im reading from only contains ints, but when I have floats in the file it doesnt seem to work, for example if I have 1.5 in the file it will only read it as 1 and it wont read any of the numbers after it.
Anyone knows whats causing this? The dynamic array where everything is saved in is a float so Im not sure what to do at this point
#include <iostream>
#include <fstream>
#include <string>
float *allocateArray(std::string fileName, int &arraySize, int &counter)
{
int a = 0;
std::ifstream myReadFile;
myReadFile.open(fileName);
float *arr = new float[arraySize]{0.0};
while (myReadFile >> a)
{
counter++;
if(counter == arraySize)
{
arr[arraySize -1] = a;
}
else
{
float *tempArray = new float[arraySize +1]{0.0};
for(int i = 0; i < arraySize; i++)
{
tempArray[i] = arr[i];
}
delete[] arr;
arraySize++;
arr = new float[arraySize];
for(int x = 0; x < arraySize; x++)
{
arr[x] = tempArray[x];
}
arr[arraySize-1] = a;
}
}
myReadFile.close();
return arr;
}
void output(float *arr, int arraySize,int counter)
{
float sum = 0.0;
for(int x = 0; x < arraySize; x++)
{
sum += arr[x];
}
float average = sum/counter;
std::cout << "Output: ";
for(int i = 0; i < arraySize; i++)
{
if(arr[i] > average)
{
std::cout << arr[i] << " ";
}
}
}
int main()
{
int arraySize = 1;
int counter = 0;
float *arr = allocateArray("input.in", arraySize, counter);
std::cout << "Input: ";
for(int x = 0; x < arraySize; x++)
{
std::cout << arr[x] << " ";
}
output(arr, arraySize, counter);
getchar();
return 0;
}
Recently I engaged in programming. In my school were told to write a program to solve systems of linear equations Gauss method, that's what I did, but I an error "'abs' cannot be used as a function", please tell me how to fix.
#include <iostream>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
// Вывод системы уравнений
void sysout(double **a, double *y, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++){
cout << a[i][j] << "*x" << j;
if (j < n - 1) {
cout << " + ";
}
}
cout << " = " << y[i] << endl;
}
return;
}
double * gauss(double **a, double *y, int n) {
double *x, max;
int k, index;
const double eps = 0.00001; // точность
x = new double[n];
k = 0;
while (k < n) {
// Поиск строки с максимальным a[i][k]
int abs;
max = abs(a[k][k]);
index = k;
for (int i = k + 1; i < n; i++) {
if (abs(a[i][k]) > max) {
max = abs(a[i][k]);
index = i;
}
}
// Перестановка строк
if (max < eps) {
// нет ненулевых диагональных элементов
cout << "Решение получить невозможно из-за нулевого столбца " ;
cout << index << " матрицы A" << endl;
return 0;
}
for (int j = 0; j < n; j++) {
double temp = a[k][j];
a[k][j] = a[index][j];
a[index][j] = temp;
}
double temp = y[k];
y[k] = y[index];
y[index] = temp;
// Нормализация уравнений
for (int i = k; i < n; i++) {
double temp = a[i][k];
if (abs(temp) < eps) continue; // для нулевого коэффициента пропустить
for (int j = 0; j < n; j++) {
a[i][j] = a[i][j] / temp;
}
y[i] = y[i] / temp;
if (i == k) continue; // уравнение не вычитать само из себя
for (int j = 0; j < n; j++) {
a[i][j] = a[i][j] - a[k][j];
}
y[i] = y[i] - y[k];
}
k++;
}
// обратная подстановка
for (k = n - 1; k >= 0; k--) {
x[k] = y[k];
for (int i = 0; i < k; i++) {
y[i] = y[i] - a[i][k] * x[k];
}
}
return x;
}
int main() {
double **a, *y, *x;
int n;
system("chcp 1251>nul");
system("cls");
cout << "Введите количество уравнений: ";
cin >> n;
a = new double*[n];
y = new double[n];
for (int i = 0; i < n; i++) {
a[i] = new double[n];
for (int j = 0; j < n; j++) {
cout << "a[" << i << "][" << j << "]= ";
cin >> a[i][j];
}
}
for (int i = 0; i < n; i++) {
cout << "y[" << i << "]= ";
cin >> y[i];
}
sysout(a, y, n);
x = gauss(a, y, n);
for (int i = 0; i < n; i++){
cout << "x[" << i << "]=" << x[i] << endl;
}
cin.get(); cin.get();
return 0;
}
Change the variable to "fabs" tried to change to "std :: abs" tried. Compiler MiGW.
If you #include <cmath> instead of stdlib.h and cstdlib then it works:
#include <iostream>
#include <cmath>
using namespace std;
// Вывод системы уравнений
void sysout(double **a, double *y, int n) {
...
Also you should remove the int abs; in the while loop.
I'm not sure why #include <cstdlib> should cause problems here - can anyone explain?
Here's an online demo of the code compiling.
I am coding a Conway's Game of Life.My task is reading from file.txt to array of strings.And then using this array as the input array of the game. I have written a code about it. But it is full of error. I don't know what is the correct way to do this.
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;
namespace gamearray {
int main()
ifstream file_("file.txt");
if(file.is_open())
{
string myArray[10];
for(int i = 0; i < 10; ++i)
{
for(int i = 0; i < 10; i++)
file >> array1[j][i];
}
}
return 0;
}
void copy(int array1[10][10], int array2[10][10])
{
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
array2[j][i] = array1[j][i];
}
}
void life(int array[10][10], char choice)
{
int temp[10][10];
copy(array, temp);
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
if(choice == 'm')
{
int count = 0;
count = array[j-1][i] +
array[j-1][i-1] +
array[j][i-1] +
array[j+1][i-1] +
array[j+1][i] +
array[j+1][i+1] +
array[j][i+1] +
array[j-1][i+1];
if(count < 2 || count > 3)
temp[j][i] = 0;
if(count == 2)
temp[j][i] = array[j][i];
if(count == 3)
temp[j][i] = 1;
}
}
}
copy(temp, array);
}
bool compare(int array1[10][10], int array2[10][10])
{
int count = 0;
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
if(array1[j][i]==array2[j][i])
count++;
}
}
if(count == 10*10)
return true;
else
return false;
}
void print(int array[10][10])
{
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
if(array[j][i] == 1)
cout << '*';
else
cout << ' ';
}
cout << endl;
}
}
int main()
{gamearray::main();
int gen0[10][10];
int todo[10][10];
int backup[10][10];
char neighborhood;
char again;
char cont;
bool comparison;
{do
{
do
{
cout << "Which neighborhood would you like to use (m): ";
cin >> neighborhood;
}while(neighborhood != 'm');
system("CLS");
int i = 0;
do
{
srand(time(NULL));
for(int j = 0; j < 10; j++)
{
for (int i = 0; i < 10; i++)
gen0[j][i] = rand() % 2;
}
if(i == 0)
copy(gen0, todo);
copy(todo, backup);
print(todo);
life(todo, neighborhood);
i++;
system("sleep .5");
if(i % 10 == 1 && i != 1)
{
cout << endl;
do
{
cout << "Would you like to continue this simulation? (y/n): ";
cin >> cont;
}while(cont != 'y' && cont != 'n');
if(cont == 'n')
break;
}
comparison = compare(todo, backup);
if(comparison == false)
system("CLS");
if(comparison == true)
cout << endl;
}while(comparison == false);
do
{
cout << "Would you like to run another simulation? (y/n): ";
cin >> again;
}while(again != 'y' && again != 'n');
}while(again == 'y');
return 0;
}
}
/*
* spielm.cpp
*
* Created on: 22.09.2016
* Author: fislam
*/
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
void GetFile();
bool MakeArray();
char ChgArray();
//char GameBoard();
const int ROW1 =10;
const int COL1 =10;
const int BOARD_ROWS(10);
const int BOARD_COLS(10);
ifstream myfile;
string filename;
char live = 'X';
char dead = '.';
char board [BOARD_ROWS][BOARD_COLS];
int main()
{
int q;
//GetFile();
if ( MakeArray() ){
for ( int i(0); i <10; i++)
ChgArray();
}
else {
cout << "Error parsing input file" << endl;
}
cin >> q;
return 0;
}
void GetFile()
{
cout<<"Enter the filename: \n";
cin>>filename;
return;
}
bool MakeArray()
{
bool ret(false);
char val;
int totCnt = BOARD_ROWS*BOARD_COLS;
myfile.open (/*filename.c_str()*/"c_str.txt");
if ( myfile.is_open() ) {
for (int r=0; r<ROW1; r++)
{
for (int c=0; c<COL1; c++)
{
myfile>>val;
if ( val == dead || val == live ) {
board[r-1][c-1] = val;
totCnt--;
}
}
}
if ( !totCnt ) {
ret = true;
}
myfile.close();
}
return ret;
}
char getNextState(char b[BOARD_ROWS][BOARD_COLS], int r, int c)
{
char ret;
return ret;
}
char ChgArray()
{
char boardTmp[BOARD_ROWS][BOARD_COLS];
for (int r=0; r<BOARD_ROWS; r++)
{
for (int c=0; c<BOARD_COLS; c++)
{
boardTmp[r][c] = getNextState(board,r,c);
cout << boardTmp[r][c];
}
cout<<endl;
}
memcpy(board,boardTmp,sizeof(board));
cout << endl;
}
Instead of the previous I wrote new. and it worked
aftert main you are missing {
in first and second loop you have i loop twice
why do you need to copy ?
you can use this function fscanf() to read your file
e.g.
File= fopen(FileName, "r");
if( File == NULL ){
printf("Impossible to open file %s ! \n",FileName);
}
if( File != NULL)
{
char text[255];
while(!feof(File))
{
fscanf(File,"%s\n",&text);
....
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm new to C++ and i have a problem during the compilation of this code. I'm traslating it from another lenguage so i'm having doubts about how pointers works. I think that the error can be made by initializzation of pointers during the loop.
Anyway the aim of the code is: store the variable results and print it out after simulated data is elaborated. My data change size every loop so I've initialized arrays inside of the loop.
using namespace std;
int* Mwa(double price[], string data[], const int period, const int size)
{
double bandup;
double banddw;
int *index;
index = new int[size];
for(int i = 0; i < size; i++)
index[i]=1;
double cmP = size/period;
double cmp = floor(cmP);
double m;
double std;
for(int i = 0; i < period; i++)
{
m = 0;
std = 0;
for(int j = i*cmp; j < (i+1)*cmp - 1; j++)
{
m += price[j];
}
m = m/cmp;
for(int j = i*cmp; j < (i+1)*cmp - 1; j++)
{
std += pow(price[j] - m,2);
}
std = pow(std/cmp, 0.5);
bandup = m + NormalCDFInv(.95)*std; // aggiungere Z value in qlc modo
banddw = m - NormalCDFInv(.95)*std; // aggiungere Z value in qlc modo
for(int j = i*cmp; j < (i+1)*cmp - 1; j++)
{
if(price[j]> bandup)
index[j] = 0;
else if(price[j]< banddw)
index[j] = 0;
else
index[j] = 1;
}
}
return index;
}
///////////////////////////////////////////////////// MAIN /////////////////////////////////////////////////////////////////////
void main()
{
const int bdays = 251;
std::string f;
cout << "Insert the path of Real Dates to be used \n";
std::cin >> f;
if(f.size() < 5)
f = "H:/Bid-Ask/C++/Bid-Ask Project/Bid-Ask Project/DateReali.txt";
cout << "Insert the path of GTR Input Data to be used \n";
std::string path;
std::cin >> path;
if(path.size() < 5)
path = "H:/Bid-Ask/";
cout << "Insert an Integer number of simulations \n";
int sim;
std::cin >> sim;
double T = 1;
int dayC = 252;
double dt = T/dayC;
int expiry[15] = {1,2,3,4,5,6,7,8,9,10,12,15,20,30,50};
std::string name = " y.csv";
int period = 15;
const double sigmaeps = 0.051;
const double sigmaeta = 0.091;
double **results;
results = new double*[sim];
for(int i =0; i < 15; i++)
results[i] = new double[sim];
double *param;
for(int rnd = 0; rnd < sim; rnd++)
{
for(int e = 0; e < period; e++)
{
stringstream ss;
ss << expiry[e];
string exp = ss.str();
string line;
std::ifstream filein;
filein.open ((path) + exp + name);
if(filein.fail())
{
std::cout << "File opening error" << std::endl;
}
else
{
double *cleanprice;
string *cleandata;
string *cleantime;
int *price2;
double *series;
double *ret;
double *price;
string *data;
string *time;
int count = 0;
while(getline(filein,line))
{
count++;
}
filein.close();
int c = count-1;
data = new string[c];
time = new string[c];
price = new double[c];
cout << exp + "\t" << count << "\n";
filein.open (path + exp + name);
for(int i = 0; i<count; i++)
{
int cols;
if(i==0)
cols = 49;
else
cols = 47;
for(int j=0; j < cols; j++)
{
getline(filein,line,',');
if(i == 0)
continue;
if(j==2)
{
data[i-1] = line.substr(1,10);
time[i-1] = line.substr(12,8);
//cout << data[i-1] + "\t";
}
else if(j == 20)
{
std::istringstream stm;
stm.str(line.substr(1,line.length()));
stm >> price[i-1];
//price[i-1] = atof((line.substr(2,line.length())).c_str());
//cout << price[i-1] << "\n";
}
else
continue;
}
}
filein.close();
price2 = Mwa(price, data, period, c);
int newc = cumsumC(price2,c);
cleantime = new string[newc];
cleanprice = new double[newc];
cleandata = new string[newc];
int Ix = 0;
for(int i=0; i<c; i++)
{
if(price2[i] == 1)
{
cleanprice[Ix]=price[i];
cleantime[Ix] = time[i];
cleandata[Ix] = data[i];
Ix++;
}
}
//for(int i = 0; i < newc; i++)
//cout << cleanprice[i] << "\t" << cleandata[i] << "\t" << cleantime[i] << "\n";
ret = SimpleReturns(cleanprice, cleandata, cleantime, newc);
std::ofstream file;
file.open( f + "/Ret.txt",std::ios::out ) ;
for(int i = 0; i < newc; i++)
file << ret[i] << "\t" << cleanprice[i] << "\t" << cleandata[i] << std::endl;
file.close();
series = KalmanFiltering(f, sigmaeps, sigmaeta, ret, cleandata, newc);
std::ofstream file1;
file1.open(f + "/Kalman.txt",std::ios::out) ;
for(int i = 0; i < bdays; i++)
file1 << series[i] << "\n";
file1.close();
param = MA1(series, bdays);
double bps = pow(abs(param[0]),.5)*param[1]*100;
cout << param[0] << "\t" << param[1] << "\t" << bps << "\r\n";
results[e][rnd] = bps;
delete[] cleantime;
delete[] cleanprice;
delete[] cleandata;
delete[] time;
delete[] data;
delete[] price;
delete[] price2;
delete[] series;
delete[] ret;
}// Else in file reading
}// loop over expiries
}// loop over simulation
std::ofstream fileR;
fileR.open( path + "Results.txt", std::ios::out);
if(fileR.fail())
{
std::cout << "File opening error" << std::endl;
}
else
{
fileR << "Expiry" << endl;
for(int e = 0; e < 15; e++)
{
stringstream ss;
ss << expiry[e];
string exp = ss.str();
fileR << exp << " y" << "\t";
for(int rnd = 0; rnd < sim; rnd++)
{
fileR << results[e][rnd] << "\t";
}
fileR << endl;
}
}
fileR.close();
for(int i =0; i < 15; i++)
delete[] results[i];
delete[] param;
}
double* MA1(double ret[], const int sizeEr)
{
double *Param = new double[1];
int gran = 100;
double* grid;
double* gridV;
grid = new double[gran]; grid[0] = -1;
gridV = new double[gran]; gridV[0] = 0;
for(int i = 1; i < gran; i++)
{
grid[i] = grid[i-1]+.02;
gridV[i] = gridV[i-1]+ .005;
//cout << grid[i] << "\n";
}
double **F;
F = new double*[gran];
for(int i = 0; i < gran; i++)
F[i]= new double[gran];
for(int a = 0; a < gran; a++)
{
double GhostTerm = 0.0;
for(int i = 2; i< sizeEr; i++)
{
double c = 0;
for(int g = 0; g < i-1; g++)
c += pow((-grid[a]),g)*(ret[i-g]);
GhostTerm += pow(c,2);
}
for(int v = 0; v < gran; v++)
{
F[a][v] = -(sizeEr-1)*.5 *log(2*3.14159*pow(grid[v],2)) + (-.5)*GhostTerm/pow(grid[v],2);
}// loop on vola
}// loop on beta
double m = -gran;
int posB = 1;
int posV = 1;
for(int i = 1; i < gran; i++)
{ for(int j = 1; j < gran; j++)
{
if(abs(grid[i]) < .01)
continue;
else
{
m = max(F[i][j],m);
if(F[i][j] == m)
{
posB = i;
posV = j;
}
}
}
}
Param[0] = grid[posB];
Param[1] = gridV[posV];
delete[] F;
delete[] grid;
return Param;
}
#endif __MA1_H_INCLUDED__
#ifndef __KALMANFILTERING_H_INCLUDED__
#define __KALMANFILTERING_H_INCLUDED__
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "MyLib.h"
#include <array>
using namespace std;
double* KalmanFiltering(std::string path, const double sigmaeps, const double sigmaeta, double ret[], string data[], int size)
{
//srand (time(NULL));
string *Realdata;
double *Sim;
std::ifstream filein;
filein.open (path);
int count = 0;
double *a;
double *P;
if(filein.fail())
{
std::cout << "File opening error" << std::endl;
return 0;
}
else
{
string line;
while(getline(filein,line))
{
count++;
}
filein.close();
Sim = new double[count];
Realdata = new string[count];
filein.open(path);
for(int i = 0; i<count; i++)
{
getline(filein,line);
Realdata[i] = line;
//cout << Realdata[i];
}
}
filein.close();
a = new double[count];
P = new double[count];
a[0]= mean(ret, size);
P[0]= variance(ret, size);
int *idx;
idx = new int[size];
for(int i=0; i < count;i++)
{
const char *chrR = Realdata[i].c_str();
double GhostR= 0.0;
for(int j=0; j < size; j++)
{
const char *chrD = data[j].c_str();
if(strcmp(chrR, chrD)== 0)
{
idx[j] = 1.0;
GhostR += ret[j];
}
else
idx[j] = 0.0;
}
if(cumsumC(idx,size) != 0)
{
double v = GhostR/cumsumC(idx,size) - a[i];
double F = P[i] + sigmaeps*sigmaeps;
a[i+1] = a[i]+(P[i]/F)*v;
P[i+1] = P[i]*(1- P[i]/F) + sigmaeta*sigmaeta;
}
else
{
a[i+1]= a[i];
P[i+1]= P[i] + sigmaeta*sigmaeta;
}
}// Loop over real data
for(int i=0; i < count;i++)
{
double GhostR = 0;
int counter = 0;
const char *chrR = Realdata[i].c_str();
for(int j=0; j < size; j++)
{
if(strcmp(chrR,data[j].c_str())== 0)
{
idx[j] = 1.0;
counter++;
GhostR += ret[j];
}
else
idx[j] = 0;
}
if(cumsumC(idx,size) != 0)
{
Sim[i] = GhostR/counter;
}
else
{
double s = rand() % 9999 + 1;
Sim[i] = a[i] + pow(P[i],2)*NormalCDFInv(s/10000);
}
}// Loop over Simulation
delete[] idx;
//delete[] a;
//delete[] P;
delete[] Realdata;
return Sim;
}// Kalman End
#endif _KALMANFILTERING_H_INCLUDED_
You do not need to use arrays for this. C++ has a nice std::vector class which requires no deletion, or manual memory management, do use it:
http://www.cplusplus.com/reference/vector/vector/
double *price;
string *data;
data = new string[c];
price = new double[c];
can be written as:
std::vector<double> price;
std::vector<std::string> data;
data.reserve(c);
price.reserve(c);
and you do not worry about allocation/deallocation of funny memory blocks.