I try to write the closest pair in n dimension, I use the divide and conquer.And I first split it into left and right part, and find their shortest path respectively and I have to find the distance accross them, when I do it , it comes to error. I have tried but cannot find the bug,where is the error in my method.
Please help me find it out!Thank in advance.
#include <vector>
#include <cmath>
#include <cfloat>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> ClosestPair(const vector< vector<double> >& points){
vector<int> closest_pair;
closest_pair.resize(2);
closest_pair[0] = 0;
closest_pair[1] = 1;
return closest_pair;
}
//utility function to calculate two point distance
double dist(vector<double> &p1, vector<double> &p2){
double sum = 0;
//n dimension point
for(int i = 0; i < p1.size(); i ++){
//cout << "i:" << i << endl;
//cout << "1:" << p1[i] << ",2:" << p2[i] << endl;
sum += (p1[i] - p2[i]) * (p1[i] - p2[i]);
}
//cout << "dist:" << sqrt(sum) << endl;
return sqrt(sum);
}
//direct calculate the distance
double bruteForce(vector<vector<double> > &p, int min_d, int max_d, int & a, int & b){
//set sum to the max_d value of double to test minimum
double sum = DBL_MAX;
//compare each distance
for(int i = min_d; i < max_d; i ++){
for(int j = i + 1; j < max_d + 1; j ++){
if(dist(p[i], p[j]) < sum){
a = i;
b = j;
sum = dist(p[i], p[j]);
}
}
}
cout << "brute:" << sum << endl;
return sum;
}
double closest(vector<vector<double> > &p, int min_d, int max_d, int& a, int& b){
//terminal condition
if(max_d - min_d <= 3){
//cout << "QQ" << endl;
return bruteForce(p, min_d, max_d, a, b);
}
//divide and conquer
else{
int a1 = 0, b1 = 0;
//cout << "haha" << endl;
int median = (max_d - min_d) / 2;
double left = closest(p, min_d, median, a1, b1);
double right = closest(p, median + 1, max_d, a, b);
if(left < right){
a = a1;
b = b1;
}
//minimun of left and right
double d = min(left, right);
//record index
int first = 0;
int last = 0;
int count = 0;
vector<vector<double> > temp;
for(int i = min_d; i < max_d; i ++){
//== d already exist
if(abs(p[i][0] - p[median][0]) < d){
if(count == 0)first = i;
count ++;
//cout << "inside:" << i << "count:" << count << endl;
temp.push_back(p[i]);
}
}
last = first + count - 1;
//cout << "first" << first << "last" << last << endl;
return min(d, closest(temp, first, last, a, b));
}
}
int main(){
int a = 0, b = 0;
//3 dimension
vector<vector<double> >test(7,vector<double>(3));
//(10,20,30)
test[0][0]= 10;
test[0][1]= 20;
test[0][2]= 30;
//(1,2,3)
test[1][0]= 1;
test[1][1]= 2;
test[1][2]= 3;
//(1000,2000,3000)
test[2][0]= 1000;
test[2][1]= 2000;
test[2][2]= 3000;
//(100,200,300)
test[3][0]= 100;
test[3][1]= 200;
test[3][2]= 300;
//(100,200,300)
test[4][0]= 100;
test[4][1]= 200;
test[4][2]= 301;
//(100,200,300)
test[5][1]= 200000;
test[5][0]= 100000;
test[5][2]= 300000;
//(100,200,300)
test[6][0]= 1000000;
test[6][1]= 2000000;
test[6][2]= 3000000;
//sort X
sort (test.begin(), test.end());
for (int i = 0; i < test.size(); i ++){
for(int j = 0; j < test[i].size(); j ++){
cout << test[i][j] << endl;
}
}
cout << "result:" << closest(test, 0, 6, a, b);
cout << "a" << a << "b" << b << endl;
return 0;
}
Change temp to something like:
vector<vector<double> > temp(7,vector<double>(3));
Related
I am writing a code to sort an array of random integers using four sorting methods bubble, selection, shell and quick sort. I'm using the same code as a rand generator to create random integers which can be sorted by the sort functions. My issue is that when I run multiple sort methods at the same time; my rand generators create the same set of integers for the arrays. How do I fix this so I can have parallel rand generators in the same program? I cannot use c++11 array or STL vector.
main.cpp
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "AssortedSorter.h"
using namespace std;
int main() {
AssortedSorter q, q2;
int UserNumOfNumbers;
int bchoice;
cout << " We pick array size (0) or you pick array size (1): ";
cin >> bchoice;
while (bchoice == 0) {
UserNumOfNumbers = 10000;
int array[UserNumOfNumbers];
srand(std::time(0));
for (int i = 0; i < UserNumOfNumbers; i++) {
array[i] = (rand() %200002) + 1;
}
cout << "\nArray Elements ::" << endl;
for (int i = 0; i < UserNumOfNumbers; i++) {
// long b = array[i];
q.quicksort(array, 0, UserNumOfNumbers);
q.bubbleSort(array, UserNumOfNumbers);
cout << " Number of Elements " << i + 1 << "::" << array[i] << endl;
// q.quicksort(array, 0, UserNumOfNumbers);
}
//q.bubbleSort(array, UserNumOfNumbers);}
// q.selectionSort(array, UserNumOfNumbers);}
return 0;
}
while (bchoice == 1) {
cout << "Enter a number between 10 and 20000: ";
cin >> UserNumOfNumbers;
while (UserNumOfNumbers < 10 || UserNumOfNumbers > 20000) {
cout << "Invalid entry! Please enter a valid value: ";
cin >> UserNumOfNumbers;
}
int array[UserNumOfNumbers];
srand(std::time(0));
for (int i = 0; i < UserNumOfNumbers; i++)
array[i] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int i = 0; i < UserNumOfNumbers; i++) {
q.bubbleSort(array, UserNumOfNumbers);
cout << " Number of Elements " << i + 1 << "::" << array[i] <</*(rand() %200002) + 1 */endl;
}
int arra[UserNumOfNumbers];
srand(std::time(NULL));
for (int j = 0; j < UserNumOfNumbers; j++)
arra[j] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int j = 0; j < UserNumOfNumbers; j++) {
q.quicksort(arra, 0, UserNumOfNumbers);
cout << " Number of Elements " << j + 1 << "::" << arra[j] << endl;
}
/*int arran[UserNumOfNumbers];
srand(std::time(0));
for (int k = 0; k < UserNumOfNumbers; k++)
arran[k] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int k = 0; k < UserNumOfNumbers; k++) {
q.selectionSort(arran, UserNumOfNumbers);
cout << " Number of Elements " << k + 1 << "::" <<(rand() %200001) + 1 << endl;}*/
break;
}
}
AssortedSorter.cpp
#include <iostream>
#include "AssortedSorter.h"
//long array;
using namespace std;
int AssortedSorter::partition(int array[], int start, int stop){
int up = start, down = stop - 1, part = array[stop];
long loopCountQ, swapCountQ;
if (stop <= start)
return start;
while (true)
{
while (array[up] < part){
/* loopCountQ++;
cout << " Loop Count++: " << loopCountQ << endl;*/
up++;}
while ((part < array[down]) && (up < down)){
/* loopCountQ++;
cout << " Loop Count--: " << loopCountQ << endl;*/
down--;}
if (up >= down)
break;
swap(array[up], array[down]);{
/* swapCountQ++;
cout << " Swap Count: " << swapCountQ << endl;*/
up++;
down--;}
}
swap(array[up], array[stop]);{
/* swapCountQ++;
cout << " Swap Count: " << swapCountQ << endl;*/
return up;}
}
int AssortedSorter ::getquicksort() const {
return *b;
}
void AssortedSorter :: quicksort(int a[], int start, int stop){
int i, s = 0, stack[20001];
// b = a;
//long * array = (a);
stack[s++] = start;
stack[s++] = stop;
while ( s > 0)
{
stop = stack[--s];
start = stack[--s];
if (start >= stop) continue;
i = partition(a, start, stop);
if
(i - start > stop - i)
{
stack[s++] = start; stack[s++] = i - 1;
stack[s++] = i + 1; stack[s++] = stop;
}
else {
stack[s++] = i + 1; stack[s++] = stop;
stack[s++] = start; stack[s++] = i - 1;
}
}
}
void AssortedSorter:: bubbleSort(int array[], int size) {
int maxElement;
int index;
//long loopcount = 0;
for (maxElement = size - 1; maxElement > 0; maxElement--) {
for (index = 0; index < maxElement; index++) {
if (array[index] > array[index + 1]) {/*loopcount++;
cout << " Loop count: " << loopcount << endl;*/
swap(array[index], array[index + 1]);
}
}
}
}
/*void AssortedSorter :: swap(int &a, int &b){
/* long int swapcount = 0;
{swapcount++;
cout << "Swap count: " << swapcount << endl;}
int temp = a;
a = b;
b = temp;
}*/
void AssortedSorter::selectionSort(int array[], int size)
{
int minIndex, minValue;
long int loopcountsel = 0;
for (int start = 0; start < (size - 1); start++)
{
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < size; index++)
{
if(array[index] < minValue)
{
loopcountsel++;
// cout << "Loop count: " << loopcountsel << endl;
}
if(array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
swap(array[minIndex], array[start]);
}
}
void AssortedSorter :: swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
AssortedSorter.h
#ifndef SORTER_ASSORTEDSORTER_H
#define SORTER_ASSORTEDSORTER_H
class AssortedSorter {
public:
void quicksort(int a[], int, int);
int getquicksort() const;
int partition(int [], int, int);
void bubbleSort(int[], int);
int getbubblesort() const;
//void swap(int & , int &);
int getswap() const;
void selectionSort(int[], int);
void swap(int &, int &);
private:
int* b;
};
#endif //SORTER_ASSORTEDSORTER_H
I'm working on a KNN algorithm with 2D arrays. It worked great when I first had the nodes be simple X and Y coordinates, but when I changed it to 2D arrays and reworked some things, I run into a funny issue.
#include <iostream>
#include <math.h>
using namespace std;
//A node
struct Node
{
int groupValue;
int col = 16; //We only have to update these to reflect the bitmap dimensions
int row = 16;
int bitmap[16][16];
float distance = -1;
//distance is the distance this node is from another
//Overloading this operator to make swapping them with insertion sort easier
Node& operator =(const Node& n)
{
for(int a = 0; a < row; a++)
{
for(int b = 0; b < col; b++)
{
bitmap[a][b] = n.bitmap[a][b];
}
}
distance = n.distance;
groupValue = n.groupValue;
return *this;
}
};
void printNode(Node n)
{
for(int a = 0; a < 16; a++)
{
for(int b = 0; b < 16; b++)
cout << n.bitmap[a][b] << ".";
cout << endl;
}
}
struct Group
{
int frequency = 0;
int id;
};
void insertionSort(Node arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i].distance;
j = i - 1;
while (j >= 0 && arr[j].distance > key)
{
Node temp = arr[j+1];
arr[j + 1] = arr[j];
arr[j] = temp;
j = j - 1;
}
arr[j + 1].distance = key;
}
}
//Takes two bitmaps and find the distance between each pixel
//using the formula d=sqrt(sum((pixel_1-pixel_2)^2))
float bitmapDistance(Node n1, Node n2)
{
Node differences; //Node's bitmap data will be the differences
//squared of each pixel from n1 and n2.
float diff;
for(int a = 0; a < n1.row; a++)
{
for(int b = 0; b < n1.col; b++)
{
diff = n1.bitmap[a][b] - n2.bitmap[a][b];
differences.bitmap[a][b] = diff * diff; //Squared difference
}
}
//Now we need to sum up the squared differences that we stored earlier
float sum;
for(int a = 0; a < n1.row; a++)
{
for(int b = 0; b < n1.col; b++)
{
sum += differences.bitmap[a][b];
}
}
//Now just take the square root of the sum and return it
if(sum < 0.01) //To fix some weird rounding issues I added this. 0.01 is arbitrary.
return 0;
return sqrt(sum);
}
/*
*Classify the node using KNN algorithm
*Multiple groups can be used, and we count how many neighbors
*belong to each group.
*n is the total amount of nodes
*k is the number of nearby neighbors
*/
int classify(Node arr[], int n, int k, Node node)
{
//Two switches for sampling, recorded as binary (0-3)
Group g0;
g0.id = 0;
Group g1;
g1.id = 1;
Group g2;
g2.id = 2;
Group g3;
g3.id = 3;
Group groupFrequency[4] = {g0, g1, g2, g3};
//For each neighbor of the given node (node) we use the distance formula
//and set it's distance member variable to this measurement
for(int a = 0; a < n; a++)
{
arr[a].distance = bitmapDistance(node, arr[a]);
//cout << arr[a].distance << ","; //<===============PROBLEM AREA===============
}
cout << endl << "----------" << endl;
insertionSort(arr, n-1);
for(int a = 0; a < n; a++)
cout << arr[a].distance << ",";
cout << endl << "----------" << endl;
//Look at all the nearest neighbors and see which group they belong to
//Increase a counter for each group the neighbor belongs to
for(int i = 0; i < k; i++)
{
if(arr[i].groupValue == 0)
groupFrequency[0].frequency++;
else if(arr[i].groupValue == 1)
groupFrequency[1].frequency++;
else if(arr[i].groupValue == 2)
groupFrequency[2].frequency++;
else if(arr[i].groupValue == 3)
groupFrequency[3].frequency++;
}
cout << "Neighboring group frequencies:" << endl;
cout << "Group Zero: " << groupFrequency[0].frequency << endl;
cout << "Group One: " << groupFrequency[1].frequency << endl;
cout << "Group Two: " << groupFrequency[2].frequency << endl;
cout << "Group Three: " << groupFrequency[3].frequency << endl;
cout << "-------------------------------------------------" << endl;
//Now we just need to look at the most common frequency and classify our node
int highestFrequency = 0;
int groupNumber = -1; //If -1 is returned, something went wrong.
for(int a = 0; a < 4; a++)
{
if(groupFrequency[a].frequency >= highestFrequency)
{
highestFrequency = groupFrequency[a].frequency;
groupNumber = groupFrequency[a].id;
}
}
return groupNumber;
}
//This stuff is just setup for testing purposes. Could this be the issue's origin?
int main()
{
Node nodeArray[200];
for(int c = 0; c < 100; c++)
{
for(int a = 0; a < 16; a++)
{
for(int b = 0; b < 16; b++)
{
nodeArray[c].groupValue = 0;
nodeArray[c].bitmap[a][b] = rand()%10;
}
}
}
for(int c = 100; c < 200; c++)
{
for(int a = 0; a < 16; a++)
{
for(int b = 0; b < 16; b++)
{
nodeArray[c].groupValue = 1;
nodeArray[c].bitmap[a][b] = 50;//rand()%10+50;
}
}
}
Node testNode;
for(int a = 0; a < 16; a++)
{
for(int b = 0; b < 16; b++)
{
testNode.bitmap[a][b] = 50;//rand()%10+50;
}
}
int num = classify(nodeArray, 200, 189, testNode);
cout << "Test node has a group classification of: " << num << endl << endl;
printNode(testNode);
cout << endl << "last node in array:" << endl;
printNode(nodeArray[199]);
cout << endl << bitmapDistance(testNode, nodeArray[199]) << endl << "first node in array:" << endl;
printNode(nodeArray[0]);
cout << bitmapDistance(testNode, nodeArray[0]);
}
The problem specifically is on line 124, in the classify() function in the for loop
for(int a = 0; a < n; a++)
{
arr[a].distance = bitmapDistance(node, arr[a]);
//cout << arr[a].distance << ","; //<====PROBLEM AREA
}
This loop is responsible for calculating the distance each node is from the sample/test node. The "arr" array is then sorted a couple of lines later via insertion sort.
If I have the for loop print out the distance values, everything works perfectly fine. I can see that all the data is properly there.
However, if I comment it out, and only print the sorted data, everything is wrong (the data does not mess up if I comment out the print statements for the sorted data, strangely enough. It's just this one line that breaks everything).
I have attached images depicting the differences between the commented line (wrong) and the uncommented line (correct) running to better show what issues I'm dealing with.
Basically, the data will lose decimal precision, have seemingly random values, and any zero value will be non-existent if I comment out this specific line.
(I know the K value should be low, but I'm using high numbers for testing right now)
Some of the output when I don't comment out the line
Some of the output when I do comment out the line
As you can see, when I comment out the line, all the sorted distance values become garbage.
What can I do to fix this?
I have an admittedly very basic problem: I need to compare two numbers of type double for >=. For some reason, however, my code evaluates to true for values I know to be less than the threshold.
EDIT: My code (the error occurs in the countTrig() method of the Antenna class):
#define k 0.0000000000000000000000138064852 // Boltzmann's constant
class Antenna{
vector<vector<double> > output;
int channels, smplrate, smpldur, samples, timethld;
double resistance, temp, bandwidth, lnanoise, lnagain, RMS;
public:
Antenna(
const int _channels, const int _smplrate, const int _smpldur,
const double _resistance, const double _temp, const double _bandwidth,
const double _lnanoise, const double _lnagain
){
channels = _channels; smplrate = _smplrate; smpldur = _smpldur;
resistance = _resistance; temp = _temp; bandwidth = _bandwidth;
lnanoise = _lnanoise; lnagain = _lnagain;
RMS = 2 * sqrt(4 * k * resistance * temp * bandwidth);
RMS *= lnagain * pow(10,(lnanoise/10));
samples = smplrate/smpldur;
timethld = 508; //= (1/smplrate) * 0.127;
}
void genThrml(int units);
void plotTrig(int timethld, double voltsthld);
void plotThrml();
int countTrig(double snrthld, int iter);
};
double fabs(double val){ if(val < 0){ val *= -1; } return val; }
void Antenna::genThrml(int units){
output.resize(samples, vector<double>(channels));
samples *= units;
gRandom->SetSeed(time(NULL));
for(int i = 0; i < samples; ++i){
for(int j = 0; j < channels; ++j){
output[i][j] = gRandom->Gaus(0,RMS);
}
}
}
void Antenna::plotThrml(){
//Filler
}
int Antenna::countTrig(double snrthld, int iter){
int count = 0;
int high = iter + timethld;
int low = iter - timethld;
if(low < 0){ low = 0; }
if(high > samples){ high = samples; }
for(int i = low; i < high; ++i){
for(int j = 0; j < channels; ++j){
if(output[i][j] >= snrthld) count++; std::cout << output[i][j] << " " << snrthld << "\n";
}
}
if(iter >= 3) return 1;
else return 0;
}
void Antenna::plotTrig(int timethld, double voltsthld){
double snrthld = voltsthld / RMS;
for(int i = 0; i < samples; ++i){
for(int j = 0; j < channels; ++j){
countTrig(snrthld, i);
}
}
}
int main(){
Antenna test(20,4000,1,50,290,500000000,1.5,60);
test.genThrml(1);
test.plotTrig(400,0.0005);
return 0;
}
With a threshold of 0.147417, I get output like this:
0.0014238
-0.00187276
I believe I understand the problem (unless there's some obvious mistake I've made and not caught), and I understand the reasoning behind floating point errors, precision, etc. I don't, however, know, what the best practice is here. What is a good solution? How can I reliably compare values of type double? This will be used in an application where it is very important that values be precise and comparisons be reliable.
EDIT: A smaller example:
int countTrig(double snrthld, int iter, vector<vector<double> > output, int timethld){
int count = 0;
int high = iter + timethld;
int low = iter - timethld;
if(low < 0){ low = 0; }
if(high > 3){ high = 3; }
for(int i = low; i < high; ++i){
for(int j = 0; j < 3; ++j){
if(fabs(output[i][j]) >= snrthld) count++; std::cout << output[i][j] << " " << snrthld << "\n";
}
}
if(iter >= 3) return 1;
else return 0;
}
void plotTrig(int timethld, double snrthld){
vector<vector<double> > output = {{0.000028382, -0.0028348329, -0.00008573829},
{0.183849939, 0.9283829020, -0.92838200021},
{-0.00292889, 0.2399229929, -0.00081009189}};
for(int i = 0; i < 3; ++i){
for(int j = 0; j < 3; ++j){
countTrig(snrthld, i, output, timethld);
}
}
}
int main(){
plotTrig(1,0.1);
return 0;
}
You have a typo.
if(output[i][j] >= snrthld) count++; std::cout << output[i][j] << " " << snrthld << "\n";
this line means
if(output[i][j] >= snrthld)
count++;
std::cout << output[i][j] << " " << snrthld << "\n";
aka
if(output[i][j] >= snrthld)
{
count++;
}
std::cout << output[i][j] << " " << snrthld << "\n";
and you want:
if(output[i][j] >= snrthld)
{
count++;
std::cout << output[i][j] << " " << snrthld << "\n";
}
The code is:
class RandomPancakeStack {
vector<int> *del;
double seen[256][256];
public:
double expectedDeliciousness(vector<int>&);
double dfs(int size, int index);
};
double RandomPancakeStack::dfs(int pos, int remain){
if(pos < 0) return 0.0;
if(seen[pos][remain] != -1) { cout << "seen\n"; return seen[pos][remain];}
double sum = 0.0;
int i;
for(i=0; i <=pos; i++){
cout << " sum += "<< (*del)[i] << " + " << dfs(i-1, remain-1) << endl;
sum += (*del)[i] + dfs(i-1, remain-1);
}
sum /= remain;
cout << " sum /=remain " << sum << endl;
seen[pos][remain] = sum;
return sum;
}
double RandomPancakeStack::expectedDeliciousness(vector<int> &d){
int N = d.size();
int i,j,k;
del = &d;
for(i=0; i < 256; i++){
for(j=0; j < 256; j++){
seen[i][j] = -1;
}
}
return dfs(N-1, N);
Is it O(N*N) ?
So I'm trying to read a matrix A from a text file, which it does correctly. A vector B is entered by the user. Then I want to perform Gaussian Elimination (Ax = b) to get the solution vector x. The values I get for x are -1.#IND and I have no idea why...I'm guessing something is going wrong in SystemSolution?
#include <iostream>
#include <vector>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
//this program does gaussian elimination for a matrix Ax=b
vector<double> SystemSolution(vector<vector<double>> A, vector<double> b)
{
//Determine and test size of a matrix
int n = A.size();
for (int i = 0; i < n; i++)
if (n != A[i].size())
throw "Error! Number of rows and columns of matrix must be equal!";
vector<double> x(b.size());
//x is the vector of solutions
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
//Finding pivot
double pivot = A[i][i];
int index = i;
for (int k = i + 1; k < n; k++)
{
if (pivot > abs(A[k][i]))
{
index = k;
pivot = A[k][i];
}
}
//Row exchange
for (int k = 0; k < n; k++)
{
double tmp = A[i][k];
A[i][k] = A[index][k];
A[index][k] = tmp;
}
//Elimination
double coefficient = -(A[j][i] / A[i][i]);
for (int k = i; k < n; k++)
{
A[j][k] += coefficient*A[i][k];
}
b[j] += coefficient*b[i];
}
}
//Back-substitution
x[n - 1] = b[n - 1] / A[n - 1][n - 1];
for (int i = n - 2; i >= 0; i--)
{
double sum = 0;
for (int j = i; j < n; j++)
{
sum += x[j] * A[i][j];
}
x[i] = (b[i] - sum) / A[i][i];
}
return x;
}
void PrintVector(const vector<double> &b)
{
for (int i = 0; i < b.size(); i++)
cout << setiosflags(ios::showpoint | ios::fixed | ios::right)
<< setprecision(4)
<< setw(8) << b[i] << endl;
}
void PrintMatrix(const vector<vector<double> > &A)
{
for (int i = 0; i < A.size(); i++)
{
for (int j = 0; j < A[i].size(); j++)
cout << setiosflags(ios::showpoint | ios::fixed | ios::right)
<< setprecision(4)
<< setw(8) << A[i][j];
cout << endl;
}
}
int main()
{
int n;
cout << "Please enter the number of rows/columns:";
cin >> n;
ifstream matrixFile;
matrixFile.open("matrix.txt");
if (matrixFile.is_open()){
//matrix A values
vector<vector<double>> A(n, vector<double>(n));
vector<double> b(n);
string line;
int col = 0;
int row = 0;
while (getline(matrixFile, line)){
istringstream stream(line);
int x;
col = 0; //reset
while (stream >> x){
A[row][col] = x;
col++;
}
row++;
}
cout << "Please enter vector b:"<<endl;
//vector b values
for (int i = 0; i < row; i++)
{
cout << "b[" << i + 1 << "]= ";
cin >> b[i];
}
vector<double> x = SystemSolution(A, b);
cout << "- SOLUTIONS -" << endl;
cout << "Matrix:" << endl;
PrintMatrix(A);
cout << "\nVector x:" << endl;
PrintVector(x);
}
else{
cout << "File failed to open!";
}
matrixFile.close();
return 0;
}
There could be some divisions by zero in your code:
double coefficient = -(A[j][i] / A[i][i]);
/* .. */
x[n - 1] = b[n - 1] / A[n - 1][n - 1];
/* .. */
x[i] = (b[i] - sum) / A[i][i];
Check out Gauss-elimination here:
Square Matrix Inversion in C
Review and debug yours.