Given some
double x;
what is the difference between
if((x>0 || (x<=0)))
and if(true)? Is there any difference? I think they are equivalent, but it seems it's not the case? Anybody knows why?
Ok, I am new to cpp and I am sorry for this question. But I truly need to solve this problem
double sigmaX = 0.1;
double sigmaY = 0.1;
SimPFilter::SimPFilter() {
totalParticles = 100;
nFilters = 2;
gsl_rng_env_setup();
rng = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set(rng, time(NULL));
}
SimPFilter::~SimPFilter() {
}
void SimPFilter::initParticles(double initX, gsl_rng* rng){
for (int i=0; i < totalParticles; i++) {
particles[i].xp = particles[i].x = 0.5 + gsl_ran_gaussian(rng, sigmaX*sigmaX);
if(i > totalParticles/2)
particles[i].xp = particles[i].x = -0.5 + gsl_ran_gaussian(rng, sigmaX*sigmaX);
particles[i].wNormalized = 1/(totalParticles/nFilters);
int j = (int)i/(totalParticles/nFilters);
particles[i].id = j;
filters[j].nParticles = (totalParticles/nFilters);
particles[i].w = particles[i].wp = particles[i].wNormalized = 1/totalParticles;
}
for(int i =0; i<nFilters; i++){
filters[i].weight = filters[i].weightPrev = 1.0/nFilters;
}
}
void SimPFilter::transition(gsl_rng* rng){
for (int i=0; i < totalParticles; i++) {
double temp = particles[i].x;
particles[i].xp = temp;
particles[i].x += gsl_ran_gaussian(rng, sigmaX*sigmaX); //the centre of each region
}
}
double SimPFilter::measure_prob(particle *p, double obser_y, gsl_rng* rng){
double x = p->x;
//cout << "x value is " << x << endl;
double prob = gsl_ran_gaussian_pdf (obser_y - (x*x), sigmaY);
//cout << "probability " << prob << endl;
std::cout << std::boolalpha;
//cout << (x>0 || (x<=0)) << endl;
if(true){
//cout << "probability2 " << prob << endl;
return prob;
}
return prob;
}
void SimPFilter::updateWeight(double obser_y, gsl_rng* rng){
for (int i=0; i < totalParticles; i++) {
double temp = particles[i].w;
particles[i].wp = particles[i].w;
particles[i].w = measure_prob(&particles[i], obser_y, rng);
}
//normalized particle weight
double eachFilterSum[nFilters];
for(int i=0; i < totalParticles; i++){
int id = particles[i].id;
eachFilterSum[id] += particles[i].w;
}
for(int i=0; i < totalParticles; i++){
particles[i].wNormalized = particles[i].w / eachFilterSum[particles[i].id];
}
//update each filter's weight
double eachFilterW[nFilters];
for(int i=0; i< totalParticles; i++){
//cout << "prticle i's weight1 "<<particles[i].w << endl;
int id = particles[i].id;
eachFilterW[id] += particles[i].wNormalized;
}
double sigmaweight =0; // simga pi n t-1 * wnt
for(int j=0; j<nFilters; j++){
sigmaweight += filters[j].weightPrev * eachFilterW[j];
}
for(int j=0; j<nFilters; j++){
double temp = filters[j].weight;
filters[j].weight = filters[j].weightPrev * eachFilterW[j] / sigmaweight;
filters[j].weightPrev = temp;
}
}
void SimPFilter::resample(gsl_rng* rng){
particle * newParticles;
newParticles = (particle*) malloc(totalParticles * sizeof(particle));
int index =(int)gsl_rng_uniform (rng)* totalParticles;
double beta = 0.0;
double maxWeight =0;
for (int i=0; i < totalParticles; i++) {
maxWeight = max(maxWeight, particles[i].wNormalized* filters[particles[i].id].weight);
}
for(int j=0; j < totalParticles; j++){
beta += (rng, 0, 2*maxWeight);
while(beta > particles[index].wNormalized * (filters[particles[index].id].weight)){
beta -= particles[index].wNormalized * (filters[particles[index].id].weight);
index = (index+1) % totalParticles;
}
newParticles[j] = particles[index];
}
for(int i=0; i<totalParticles; i++){
particles[i] = newParticles[i];
particles[i].w = particles[i].wNormalized = particles[i].wp =1/filters[particles[i].id].nParticles;
}
//update each filter particles number
vector<int> countP;
for(int i=0; i<nFilters; i++){
countP.push_back(0);
}
for(int i=0; i< totalParticles; i++){
countP.at(particles[i].id)++;
}
for(int i=0; i< nFilters; i++){
filters[i].nParticles = countP.at(i);
}
for(int i=0; i< nFilters;i++)
cout << "n particle value is " << filters[i].nParticles << endl;
free(newParticles);
}
`
in the measure_prob function, I find out, if(true) or if(x>=0 || x<0) give different result. When if(true) it could track two objects, but when I use if(x>=0 || x<0) it will converge to one object quickly. I am really confused...
Example :
double x = log2(-1); // Evaluates to NAN
if (x>0 || (x<=0)) {
printf("True\n");
}
else {
printf("False\n");
}
OUTPUT
False
Hence they are not equivalent. NAN stands for Not A Number so it is neither greater than 0 nor is it equal to or less than zero cause it is not a number.
Related
I have coded up a gauss seidel method that works just fine but i cannot seem to figure out how to convert that to jacobi... I know it should be easy so i must be missing something simple. For the assignment i had to make my own vector and matrix classes so that is why Vector is capital and called differently. Here is my working gauss seidel code:
else if (mode == 3) {
Vector temp;
temp.allocateData(b.numElems());
Vector old = temp;
Vector sum;
double f = 50;
int y = 4;
double tol = 1e-12;
double error = 10;
int max = 999999;
int count = 0;
while ( error > tol && max > count) {
for (int i = 0; i < row_; i++) {
temp.setVal(i, b.getVal(i) / M[i][i]);
for (int j = 0; j < col_; j++) {
if (j == i) {
continue;
}
temp.setVal(i, temp.getVal(i) - ((M[i][j] / M[i][i]) * temp.getVal(j)));
old.setVal(j, temp.getVal(i));
}
cout<<"x"<< i + 1 << "="<< temp.getVal(i) <<" \n";
error = abs(temp.getVal(i)-old.getVal(i))/abs(temp.getVal(i));
old = temp;
}
cout << "\n";
count++;
}
}
and here is my attempt at jacobi:
else if (mode == 2) {
Vector temp;
temp.allocateData(b.numElems());
Vector old = temp;
Vector sum;
double f = 50;
int y = 4;
double tol = 1e-12;
double error = 10;
int max = 999999;
int count = 0;
while ( error > tol && max > count) {
old.allocateData(b.numElems());
for (int i = 0; i < row_; i++) {
old.setVal(i, temp.getVal(i));
temp.setVal(i, b.getVal(i) / M[i][i]);
for (int j = 0; j < col_; j++) {
if (j == i) {
continue;
}
temp.setVal(i, temp.getVal(i) - ((M[i][j] / M[i][i]) * old.getVal(j)));
}
cout<<"x"<< i + 1 << "="<< temp.getVal(i) <<" \n";
error = abs(temp.getVal(i)-old.getVal(i))/abs(temp.getVal(i));
}
cout << "\n";
count++;
}
}
thanks everyone ahead of time for the help!!!
a scheduling problem that wants to minimize a weighted completion time
I would like to pass the image problem to the c++ language and solve it with cplex solver.
Problem:
Min ∑WiCi
xi ∈ 0,1
t= ∆ + ∑_{i} xi*pi1
Ci1 = ∑_{j=1}^{i} xj*pj1
Ci2 = t + ∑_{j=1}^{i} (1−xj)*pj2
Ci ≥ Ci1
Ci ≥ Ci2−Ωxi
Ω = ∆ + ∑_i max(pi1, pi2)
The goal is to minimize the weighted completion time of a problem with one machine with at most one machine reconfiguration. I have a boolean variable Xi that tells me if the job is done before or after the reconfiguration. The variable t is the instant after the reconfiguration(delta is the time to reconfigure the machine). pi1 is the processing time in configuration 1 and pi2 is the processing time in configuration 2. Besides, I have restrictions due to Ci (completion time of a job i).
The example of code I made is not working. I know I have a problem writing the C variable (but I don't know how to solve it).
#include <iostream>
#include <ilcplex/ilocplex.h>
#include <ilcp/cp.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int nbJob = 4;
int delta = 2;
int nbConf = 2;
vector<int> w_job;
w_job.push_back(1); w_job.push_back(1); w_job.push_back(1); w_job.push_back(1);
vector<vector<int>>p_job;
p_job.resize(nbJob);
p_job[0].push_back(6); p_job[0].push_back(3);
p_job[1].push_back(1); p_job[1].push_back(2);
p_job[2].push_back(10); p_job[2].push_back(2);
p_job[3].push_back(1); p_job[3].push_back(9);
int max_p = 0;
int aux;
for (size_t i = 0; i < nbJob - 1; i++) {
aux = max(p_job[i][0], p_job[i][1]);
max_p = max(max_p, aux);
}
cout << max_p << endl;
int max_w = 0;
aux = 0;
for (size_t i = 0; i < nbJob - 1; i++) {
aux = max(w_job[i], w_job[i + 1]);
max_w = max(aux, max_w);
}
cout << max_w << endl;
int omega = 0;
for (size_t i = 0; i < nbJob; i++) {
omega += max(p_job[i][0], p_job[i][1]);
}
omega += delta;
cout << omega << endl;
try {
IloEnv env;
IloModel model(env);
IloBoolVarArray x(env, nbJob);
for (size_t i = 0; i < nbJob; i++) {
IloBoolVar xi(env, 0, 1, "xi");
x[i] = xi;
}
IloArray<IloExprArray> C(env, nbJob);
for (size_t i = 0; i < nbJob; i++) {
IloExprArray Ci(env);
for (size_t j = 0; j < nbConf; j++) {
IloExpr Cij(env);
Ci.add(Cij);
}
C[i] = Ci;
}
IloNumVarArray C_final(env, nbJob);
for (size_t i = 0; i < nbJob; i++) {
IloNumVar C_finali(env, 0, IloInfinity, ILOINT); //
C_final[i] = C_finali;
}
IloExpr t(env);
for (int i = 0; i < nbJob; i++) {
t += x[i] * p_job[i][0];
}
t += delta;
for (size_t i = 0; i < nbJob; i++) {
for (size_t j = 0; j < nbJob; j++) {
if (j <= i) {
C[i][0] += x[j] * p_job[j][0];
}
}
}
for (size_t i = 0; i < nbJob; i++) {
for (size_t j = 0; j < nbJob; j++) {
if (j <= i) {
C[i][1] += ((1 - x[j]) * p_job[j][1]);
}
}
C[i][1] += t;
}
for (size_t i = 0; i < nbJob; i++) {
model.add(C_final[i] >= C[i][0]);
}
for (size_t i = 0; i < nbJob; i++) {
model.add(C_final[i] >= C[i][1] - (omega * x[i]));
}
IloExpr wiCi(env);
for (size_t i = 0; i < nbJob; i++) {
wiCi += w_job[i] * C_final[i];
}
model.add(IloMinimize(env, wiCi));
IloCplex solver(model);
solver.solve();
for (int i = 0; i < nbJob; i++) {
cout << "C " << i + 1 << " = " << solver.getValue(C_final[i]) << " x" << i+1 << " = " << solver.getValue(x[i]) << endl;
}
cout << endl;
cout << "t = " << solver.getValue(t) << endl;
cout << "wiCi = " << solver.getObjValue() << endl << endl;
}
catch (IloException e) {
cout << e.getMessage();
}
}
this is the code that is have i am trying to get the take the for loops that i have and condense them
into a loop but i am not sure how. If there is anyone that can help me out i would appreciate it. The fist set of for loops are taking the inverse and then it is muiltiplying through the positions of the array. Right now the for loops are going through on position for each loop and i know there is a better way but i cant think of how to do it.
using namespace std;
#include<iostream>
#include<fstream>
#include<iomanip>
#include<Windows.h>
// User-defined function declarations (prototypes)
void readit();
void calcit(float[5][6], float[5][6]);
void writeit(float [5][6], float[5][6], float[5]);
// Declaration and definition of the main()
int main()
{
readit();
return 0;
}
void readit()
{
// Local variable declarations
float origarray[5][6], reducedarray[5][6];
// Filestream declaration and error trap
ifstream infile("C:\\EGR111\\rowechelondata.txt");
if(!infile)
{
cout << "There is no file, or the filestream is corrupted. Correct the problem and "
<< "try again!";
Sleep(2000);
exit(0);
}
// File read. 'i' is row index and 'j' is column index.
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
infile >> origarray[i][j];
reducedarray[i][j] = origarray[i][j];
}
}
calcit(origarray, reducedarray);
}
void calcit(float origarray[5][6], float reducedarray[5][6])
{
// Local variable declaration
float roots[5] = {};
cout << setprecision(4) << endl;
// Multiply first row by its leading coefficient, such that the result is '1'
for(int i = 0; i < 1; i++)
{
for(int j = 0; j < 6; j++)
{
reducedarray[i][j] = origarray[i][j] * (1.0 / origarray[0][0]);
}
}
// Multiply second row by its leading coefficient, such that the result is '1'
for(int i = 1; i < 2; i++)
{
for(int j = 0; j < 6; j++)
{
reducedarray[i][j] = origarray[i][j] * (1.0 / origarray[1][0]);
}
}
// Multiply third row by its leading coefficient, such that the result is '1'
for(int i = 2; i < 3; i++)
{
for(int j = 0; j < 6; j++)
{
reducedarray[i][j] = origarray[i][j] * (1.0 / origarray[2][0]);
}
}
// Multiply fourth row by its leading coefficient, such that the result is '1'
for(int i = 3; i < 4; i++)
{
for(int j = 0; j < 6; j++)
{
reducedarray[i][j] = origarray[i][j] * (1.0 / origarray[3][0]);
}
}
// Multiply fifth row by its leading coefficient, such that the result is '1'
for(int i = 4; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
reducedarray[i][j] = origarray[i][j] * (1.0 / origarray[4][0]);
}
}
// Subtract the first row of the reduced array into the subsequent rows
for(int i = 1; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] - reducedarray[0][j];
}
}
// Multiply array position [1][1] by its leading coefficient, such that the result is '1'
for(int i = 1; i < 2; i++)
{
for(int j = 1; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[1][1]);
}
}
// Multiply array position [2][1] by its leading coefficient, such that the result is '1'
for(int i = 2; i < 3; i++)
{
for(int j = 1; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[2][1]);
}
}
// Multiply array position [3][1] by its leading coefficient, such that the result is '1'
for(int i = 3; i < 4; i++)
{
for(int j = 1; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[3][1]);
}
}
// Multiply array position [4][1] by its leading coefficient, such that the result is '1'
for(int i = 4; i < 5; i++)
{
for(int j = 1; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[4][1]);
}
}
// Subtract the second row of the reduced array into the subsequent rows
for(int i = 2; i < 5; i++)
{
for(int j = 1; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] - reducedarray[1][j];
}
}
// Multiply array position [2][2] by its leading coefficient, such that the result is '1'
for(int i = 2; i < 3; i++)
{
for(int j = 2; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[2][2]);
}
}
// Multiply array position [3][2] by its leading coefficient, such that the result is '1'
for(int i = 3; i < 4; i++)
{
for(int j = 2; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[3][2]);
}
}
// Multiply array position [4][2] by its leading coefficient, such that the result is '1'
for(int i = 4; i < 5; i++)
{
for(int j = 2; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[4][2]);
}
}
// Subtract the third row of the reduced array into the subsequent rows
for(int i = 3; i < 5; i++)
{
for(int j = 2; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] - reducedarray[2][j];
}
}
// Multiply array position [3][3] by its leading coefficient, such that the result is '1'
for(int i = 3; i < 4; i++)
{
for(int j = 3; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[3][3]);
}
}
// Multiply array position [4][3] by its leading coefficient, such that the result is '1'
for(int i = 4; i < 5; i++)
{
for(int j = 3; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[4][3]);
}
}
// Subtract the fourth row of the reduced array into the subsequent row
for(int i = 4; i < 5; i++)
{
for(int j = 3; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] - reducedarray[3][j];
}
}
// Multiply array position [4][4] by its leading coefficient, such that the result is '1'
for(int i = 4; i <= 4; i++)
{
for(int j = 4; j < 6; j++)
{
reducedarray[i][j] = reducedarray[i][j] * (1.0 / reducedarray[4][4]);
}
}
// Back solve to assign roots for each row
for(int i = 4; i >= 0; i--)
{
for(int j = 5; j >= 0; j--)
{
roots[i] = reducedarray[4][5];
roots[4] = roots[i];
}
}
for(int i = 3; i >= 0; i--)
{
for(int j = 5; j >= 0; j--)
{
roots[i] = reducedarray[3][5] - (reducedarray[3][4] * roots[4]);
roots[3] = roots[i];
}
}
for(int i = 2; i >= 0; i--)
{
for(int j = 5; j >= 0; j--)
{
roots[i] = reducedarray[2][5] - (reducedarray[2][4] * roots[4]) -
(reducedarray[2][3] * roots[3]);
roots[2] = roots[i];
}
}
for(int i = 1; i >= 0; i--)
{
for(int j = 5; j >= 0; j--)
{
roots[i] = reducedarray[1][5] - (reducedarray[1][4] * roots[4]) -
(reducedarray[1][3] * roots[3]) - (reducedarray[1][2] * roots[2]);
roots[1] = roots[i];
}
}
for(int i = 0; i >= 0; i--)
{
for(int j = 5; j >= 0; j--)
{
roots[i] = reducedarray[0][5] - (reducedarray[0][4] * roots[4]) -
(reducedarray[0][3] * roots[3]) - (reducedarray[0][2] * roots[2]) -
(reducedarray[0][1] * roots[1]);
roots[0] = roots[i];
}
}
writeit(origarray, reducedarray, roots);
}
void writeit(float origarray[5][6], float reducedarray[5][6], float roots[5])
{
cout << "The Original Array" << endl << endl;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
cout << setw(6) << origarray[i][j] << setw(4) << "";
}
cout << endl << endl;
}
cout << endl << endl;
cout << "The Reduced Array" << endl << endl;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
cout << setw(6) << reducedarray[i][j] << setw(4) << "";
}
cout << endl << endl;
}
cout << endl << endl;
cout << "The Roots of the equations are: " << endl << endl;
cout << setw(6) << "A = " << setw(6) << roots[0] << endl << endl;
cout << setw(6) << "B = " << setw(6) << roots[1] << endl << endl;
cout << setw(6) << "C = " << setw(6) << roots[2] << endl << endl;
cout << setw(6) << "D = " << setw(6) << roots[3] << endl << endl;
cout << setw(6) << "E = " << setw(6) << roots[4] << endl << endl;
cout << endl << endl;
}
Where m=number of columns in matrix and n=number of rows in matrix.
Just the needed segment:
void calcit(float origarray[5][6], float reducedarray[5][6])
{
float roots[5] = {};
int n=5,m=6;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
reducedarray[i][j]=origarray[i][j]*(1.0/origarray[i][0]);
}
}
for(int i = 1; i < 5; i++){
for(int j = 0; j < 6; j++){
reducedarray[i][j] -= reducedarray[0][j];
}
}
int num=1;
for(int i=1;i<m;i++){
for(int j=num;j<n;j++){
for(int k=i;k<m;k++)
reducedarray[j][k] = reducedarray[j][k] * (1.0 / reducedarray[j][i]);
}
for(int j=num+1;j<n;j++){
for(int k=num;k<m;k++){
reducedarray[j][k] -= reducedarray[i][k];
}
}
num++;
}
for(int i=n-1;i>=0;i--){
float ans=reducedarray[i][m-1];
for(int j=m-2;j>=i+1;j--){
ans-=(reducedarray[i][j]*roots[j]);
}
roots[i]=ans;
}
writeit(origarray, reducedarray, roots);
}
Whole code:
#include<iostream>
#include<fstream>
#include<iomanip>
#include<Windows.h>
using namespace std;
// User-defined function declarations (prototypes)
void readit();
void calcit(float[5][6], float[5][6]);
void writeit(float [5][6], float[5][6], float[5]);
// Declaration and definition of the main()
int main()
{
readit();
return 0;
}
void readit()
{
// Local variable declarations
float origarray[5][6], reducedarray[5][6];
// Filestream declaration and error tra
cout << setprecision(4) << endl;
// File read. 'i' is row index and 'j' is column index.
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
cin >> origarray[i][j];
reducedarray[i][j] = origarray[i][j];
}
}
calcit(origarray, reducedarray);
}
void calcit(float origarray[5][6], float reducedarray[5][6])
{
float roots[5] = {};
int n=5,m=6;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
reducedarray[i][j]=origarray[i][j]*(1.0/origarray[i][0]);
}
}
for(int i = 1; i < 5; i++){
for(int j = 0; j < 6; j++){
reducedarray[i][j] -= reducedarray[0][j];
}
}
int num=1;
for(int i=1;i<m;i++){
for(int j=num;j<n;j++){
for(int k=i;k<m;k++)
reducedarray[j][k] = reducedarray[j][k] * (1.0 / reducedarray[j][i]);
}
for(int j=num+1;j<n;j++){
for(int k=num;k<m;k++){
reducedarray[j][k] -= reducedarray[i][k];
}
}
num++;
}
for(int i=n-1;i>=0;i--){
float ans=reducedarray[i][m-1];
for(int j=m-2;j>=i+1;j--){
ans-=(reducedarray[i][j]*roots[j]);
}
roots[i]=ans;
}
writeit(origarray, reducedarray, roots);
}
void writeit(float origarray[5][6], float reducedarray[5][6], float roots[5])
{
cout << "The Original Array" << endl << endl;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
cout << setw(6) << origarray[i][j] << setw(4) << "";
}
cout << endl << endl;
}
cout << endl << endl;
cout << "The Reduced Array" << endl << endl;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
cout << setw(6) << reducedarray[i][j] << setw(4) << "";
}
cout << endl << endl;
}
cout << endl << endl;
cout << "The Roots of the equations are: " << endl << endl;
for(int i=0;i<5;i++){
cout<<(char)('A'+i)<<" = "<<setw(6)<<roots[i]<<endl;
}
}
Please, kindly, check if it is working. If it does not work, please notify me in the comments of this post.
Also, i'm not sure why are you using double endl (cout<<endl<<endl;),there is an alternative to this: cout<<"\n\n"; (note that this doesn't flush the output buffer)
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.
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.