Reliable comparison of double - c++

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";
}

Related

vector is out of range,but why?

It says my vector is out of range for ArrayD. But I do not understand why. Everything else works. Is says that the vector is out of range after double deez. Therefore, it will not ascend fully.
using namespace std;
void hello();
void Infile();
double x, y, z;
double P, B;
int E = 0;
double V[16];
double C[16];
double D[16];
int m, n;
int main()
{
Infile();
return 0;
}
void Infile()
{
ifstream fileA("P_matrix.txt");
ifstream fileB("b_matrix.txt");
ifstream fileC("d_matrix.txt");
vector<double>ArrayP;
vector<double>ArrayB;
vector<double>ArrayD;
cout << "P Matrix Values \n";
while (fileA.good())
{
fileA >> P;
ArrayP.push_back(P);
}
for (int i = 0; i<ArrayP.size(); i++)
{
cout << ArrayP[i] << ",";
}
system("pause");
cout << "B Matrix Values \n";
while (fileB.good())
{
fileB >> B;
ArrayB.push_back(B);
}
for (int j = 0; j < 16; j++)
{
cout << ArrayB[j] << ",";
}
system("pause");
while (fileC.good())
{
fileC >> D;
ArrayD.push_back(D);
}
for (int k = 0; k <16; k++)
{
cout << ArrayD[k] << ",";
}
system("pause");
for (int m = 0; m < 16; m++)
{
V[m] = ArrayP[m] * ArrayB[m];
cout << V[m] << ",";
}
system("pause");
for (int n = 0; n < 16; n++)
{
C[n] = V[n] * ArrayD[n];
cout << C[n] << ",";
}
//outfile.close();
system("pause");
double deez;
for (int d = 0; d < 16; d++) //acscending
{
for (int q = 0; q < 16; q++)
{
if (ArrayD[q] < ArrayD[q - 1])
{
deez = ArrayD[q];
ArrayD[q] = ArrayD[q - 1];
ArrayD[q - 1] = deez;
}
}
}
for (int q = 0; q < 16; q++)
cout << C[q] << ",";
system("pause");
double nutz;
for (int d = 0; d < 16; d++) //descending
{
for (int q = 0; q < 16; q++)
{
if (V[q] < V[q + 1])
{
nutz = V[q];
V[q] = V[q + 1];
V[q + 1] = nutz;
}
}
}
for (int q = 0; q < 16; q++)
cout << V[q] << ",";
system("pause");
return;
}
Here, q starts at zero, so you are attempting to access index [-1].
ArrayD[q - 1]
When iterating over ArrayP, you correctly do:
for (int i = 0; i<ArrayP.size(); i++)
However for ArrayB and ArrayC, you seem to assume there are only ever 16 elements in those arrays (are you sure?). I can't see any evidence that the arrays are restricted to always having 16 elements in code, so that could also be the issue.
Later still, you then seem to assume all of those arrays have 16 elements?
for (int m = 0; m < 16; m++)
{
V[m] = ArrayP[m] * ArrayB[m];
cout << V[m] << ",";
}
Those are the obvious places that could cause an out of range error.

Finding the maximum sum in a field of numbers

I have to write a program that sums up sequential elements of an array and outputs the maximum sum. As you will see my algorithm won't work if all elements are negative.
#include <iostream>
int main()
{
int nums[1000] = {-1,-3,-4,-2,-5,-1,-9,-4,-2,-2};
int sums[100][100];
int n = 9;
for(int i = 0; i <= n; i++) {
for(int j = n; j >= i; j--) {
for(int k = j; k >= i; k--) {
sums[i][j] += nums[k];
}
}
}
int max_sum = 0;
int max_begin;
int max_end;
for(int i = 0; i <= n; i++) {
for(int j = i+1; j <= n; j++){
std::cout << "i = " << i << " j = " << j << ": " << sums[i][j] << "\n";
if(max_sum < sums[i][j]) {
max_sum = sums[i][j];
max_begin = i;
max_end = j;
}
}
}
std::cout << "Maximum: " << max_sum << " bei i = " << max_begin << " bis j = " << max_end;
return 0;
}
I already tried this solution
#include <climits>
...
int max_sum = INT_MIN;
...
While this works perfectly fine we didn't have climits in our lecture yet so I'm looking for another way.
Change to:
int max_sum = sums[0][0];
This way you will never have to worry about the range of numbers.
This is one of the main motivations for a std::optional type (when all values in a range are valid). If you cannot use it, we can imitate it for our purposes with a simple boolean:
bool max_set = false;
int max_sum = 0;
// ...
if (!max_set || max_sum < sums[i][j]){
max_set = true;
max_sum = sums[i][j];
}
We can make a simple class to further imitate it if we'd like (untested code):
class optional_int{
bool is_set = false;
int value = 0;
public:
bool operator()() const{return is_set;}
int& operator=(int _value){value = _value; is_set=true; return value;}
int& get(){
if (!is_set){throw std::logic_error("attempting to access unset optional");}
return value;
};
optional_int max_sum;
//...
if (!max_sum || max_sum.get() < sums[i][j]){
max_sum = sums[i][j];
}
We can continue to make this type more and more generic, but we'd only be re-implementing std::optional

Smith Waterman for C++ (Visual Studio 14.0)

I would like to kill two birds with one stone, as the questions are very similiar:
1:
I followed this code on github Smith Waterman Alignment to create the smith-waterman in C++. After some research I understood that implementing
double H[N_a+1][N_b+1]; is not possible (anymore) for the "newer" C++ versions. So to create a constant variable I changed this line to:
double **H = new double*[nReal + 1];
for (int i = 0; i < nReal + 1; i++)
H[i] = new double[nSynth + 1];
and also the same scheme for int I_i[N_a+1][N_b+1], I_j[N_a+1][N_b+1]; and so one (well, everywhere, where a two dimensional array exists). Now I'm getting the exception:
Unhandled exception at 0x00007FFF7B413C58 in Smith-Waterman.exe: Microsoft C
++ exception: std :: bad_alloc at location 0x0000008FF4F9FA50.
What is wrong here? Already debugged, and the program throws the exceptions above the for (int i = 0; i < nReal + 1; i++).
2: This code uses std::strings as parameters. Would it be also possible to create a smith waterman algortihm for cv::Mat?
For maybe more clarification, my full code looks like this:
#include "BinaryAlignment.h"
#include "WallMapping.h"
//using declarations
using namespace cv;
using namespace std;
//global variables
std::string bin;
cv::Mat temp;
std::stringstream sstrMat;
const int maxMismatch = 2;
const float mu = 0.33f;
const float delta = 1.33;
int ind;
BinaryAlignment::BinaryAlignment() { }
BinaryAlignment::~BinaryAlignment() { }
/**
*** Convert matrix to binary sequence
**/
std::string BinaryAlignment::matToBin(cv::Mat src, std::experimental::filesystem::path path) {
cv::Mat linesMat = WallMapping::wallMapping(src, path);
for (int i = 0; i < linesMat.size().height; i++) {
for (int j = 0; j < linesMat.size().width; j++) {
if (linesMat.at<Vec3b>(i, j)[0] == 0
&& linesMat.at<Vec3b>(i, j)[1] == 0
&& linesMat.at<Vec3b>(i, j)[2] == 255) {
src.at<int>(i, j) = 1;
}
else {
src.at<int>(i, j) = 0;
}
sstrMat << src.at<int>(i, j);
}
}
bin = sstrMat.str();
return bin;
}
double BinaryAlignment::similarityScore(char a, char b) {
double result;
if (a == b)
result = 1;
else
result = -mu;
return result;
}
double BinaryAlignment::findArrayMax(double array[], int length) {
double max = array[0];
ind = 0;
for (int i = 1; i < length; i++) {
if (array[i] > max) {
max = array[i];
ind = i;
}
}
return max;
}
/**
*** Smith-Waterman alignment for given sequences
**/
int BinaryAlignment::watermanAlign(std::string seqSynth, std::string seqReal, bool viableAlignment) {
const int nSynth = seqSynth.length(); //length of sequences
const int nReal = seqReal.length();
//H[nSynth + 1][nReal + 1]
double **H = new double*[nReal + 1];
for (int i = 0; i < nReal + 1; i++)
H[i] = new double[nSynth + 1];
cout << "passt";
for (int m = 0; m <= nSynth; m++)
for (int n = 0; n <= nReal; n++)
H[m][n] = 0;
double temp[4];
int **Ii = new int*[nReal + 1];
for (int i = 0; i < nReal + 1; i++)
Ii[i] = new int[nSynth + 1];
int **Ij = new int*[nReal + 1];
for (int i = 0; i < nReal + 1; i++)
Ij[i] = new int[nSynth + 1];
for (int i = 1; i <= nSynth; i++) {
for (int j = 1; j <= nReal; j++) {
temp[0] = H[i - 1][j - 1] + similarityScore(seqSynth[i - 1], seqReal[j - 1]);
temp[1] = H[i - 1][j] - delta;
temp[2] = H[i][j - 1] - delta;
temp[3] = 0;
H[i][j] = findArrayMax(temp, 4);
switch (ind) {
case 0: // score in (i,j) stems from a match/mismatch
Ii[i][j] = i - 1;
Ij[i][j] = j - 1;
break;
case 1: // score in (i,j) stems from a deletion in sequence A
Ii[i][j] = i - 1;
Ij[i][j] = j;
break;
case 2: // score in (i,j) stems from a deletion in sequence B
Ii[i][j] = i;
Ij[i][j] = j - 1;
break;
case 3: // (i,j) is the beginning of a subsequence
Ii[i][j] = i;
Ij[i][j] = j;
break;
}
}
}
//Print matrix H to console
std::cout << "**********************************************" << std::endl;
std::cout << "The scoring matrix is given by " << std::endl << std::endl;
for (int i = 1; i <= nSynth; i++) {
for (int j = 1; j <= nReal; j++) {
std::cout << H[i][j] << " ";
}
std::cout << std::endl;
}
//search H for the moaximal score
double Hmax = 0;
int imax = 0, jmax = 0;
for (int i = 1; i <= nSynth; i++) {
for (int j = 1; j <= nReal; j++) {
if (H[i][j] > Hmax) {
Hmax = H[i][j];
imax = i;
jmax = j;
}
}
}
std::cout << Hmax << endl;
std::cout << nSynth << ", " << nReal << ", " << imax << ", " << jmax << std::endl;
std::cout << "max score: " << Hmax << std::endl;
std::cout << "alignment index: " << (imax - jmax) << std::endl;
//Backtracing from Hmax
int icurrent = imax, jcurrent = jmax;
int inext = Ii[icurrent][jcurrent];
int jnext = Ij[icurrent][jcurrent];
int tick = 0;
char *consensusSynth = new char[nSynth + nReal + 2];
char *consensusReal = new char[nSynth + nReal + 2];
while (((icurrent != inext) || (jcurrent != jnext)) && (jnext >= 0) && (inext >= 0)) {
if (inext == icurrent)
consensusSynth[tick] = '-'; //deletion in A
else
consensusSynth[tick] = seqSynth[icurrent - 1]; //match / mismatch in A
if (jnext == jcurrent)
consensusReal[tick] = '-'; //deletion in B
else
consensusReal[tick] = seqReal[jcurrent - 1]; //match/mismatch in B
//fix for adding first character of the alignment.
if (inext == 0)
inext = -1;
else if (jnext == 0)
jnext = -1;
else
icurrent = inext;
jcurrent = jnext;
inext = Ii[icurrent][jcurrent];
jnext = Ij[icurrent][jcurrent];
tick++;
}
// Output of the consensus motif to the console
std::cout << std::endl << "***********************************************" << std::endl;
std::cout << "The alignment of the sequences" << std::endl << std::endl;
for (int i = 0; i < nSynth; i++) {
std::cout << seqSynth[i];
};
std::cout << " and" << std::endl;
for (int i = 0; i < nReal; i++) {
std::cout << seqReal[i];
};
std::cout << std::endl << std::endl;
std::cout << "is for the parameters mu = " << mu << " and delta = " << delta << " given by" << std::endl << std::endl;
for (int i = tick - 1; i >= 0; i--)
std::cout << consensusSynth[i];
std::cout << std::endl;
for (int j = tick - 1; j >= 0; j--)
std::cout << consensusReal[j];
std::cout << std::endl;
int numMismatches = 0;
for (int i = tick - 1; i >= 0; i--) {
if (consensusSynth[i] != consensusReal[i]) {
numMismatches++;
}
}
viableAlignment = numMismatches <= maxMismatch;
return imax - jmax;
}
Thanks!

What is the run time complexity of this program?

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) ?

errors in closest pair in n dimension

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));