C++: void value not ignored as it ought to be [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
The error is with:
estimate1 = leibnizPi (nTerms, estimatedV1);
&
estimate2 = wallisPi (nTerms, estimatedValue2);
I'm thinking it has to do with the way it is set up to reference the estimatedValue in the function, or the way it is being called is incorrect.
Any help is much appreciated!
NOTE: HAS TO REMAIN VOID. Sorry about that.
#include <iostream>
#include <cmath>
//
// This program will be used in the second assignment (functions)
//
using namespace std;
const double PI = 3.14159265358979323846;
void leibnizPi (int numberofterms, double &estimatedValue1 )
{
double sign = 1.0;
double sum = 0.0;
for (int i = 0; i < numberofterms; ++i) {
double denominator = 2.0 * i + 1.0;
double term = 4.0 / denominator;
sum = sum + sign * term;
sign = -sign;
}
estimatedValue1 = sum;
}
void wallisPi (int numberofterms, double &estimatedValue2)
{
double product = 1.0;
for (int i = 1; i < numberofterms; ++i) {
double r = 2.0*i;
r = r*r;
double term = r/(r-1.0);
product = product * term;
}
estimatedValue2 = 2.0 * product;
}
double abstractError (double computedValue);
double relativeError (double computedValue);
int main (int argc, char** argv) {
double estimate1 = 0;
double absErr1 = 0;
double relErr1 = 0;
double estimate2 = 0;
double absErr2 = 0;
double relErr2 = 0;
double estimatedV1 = 0;
double estimatedValue2 = 0;
for (int nTerms = 1; nTerms < 100001; nTerms = nTerms * 4) {
// Estimate Pi by two different methods
// Leibniz' sum
estimate1 = leibnizPi (nTerms, estimatedV1);
absErr1 = abstractError (estimate1);
relErr1 = relativeError (estimate1);
// Wallis' product
estimate2 = wallisPi (nTerms, estimatedValue2);
absErr2 = abstractError (estimate2);
relErr2 = relativeError (estimate2);
cout << "After " << nTerms << " terms\n";
cout << "Leibniz' estimate: "<< estimate1 << "\n";
cout << "Absolute error: " << absErr1
<< "\tRelative error: " << relErr1
<< "\n";
cout << "Wallis' estimate: "<< estimate2 << "\n";
cout << "Absolute error: " << absErr2
<< "\tRelative error: " << relErr2
<< "\n";
cout << endl;
}
return 0;
}
double abstractFunction (double computedValue)
{
double abstractError = abs(computedValue - PI);
return abstractError;
}
double relativeFunction (double computedValue){
double relativeError1 = abs(computedValue - PI) / PI;
return relativeError1;
}

You cannot use the return value of a function returning void, because there isn't one. Instead, you may want to try something like this:
double leibnizPi (int numberofterms, double &estimatedValue1 )
{
double sign = 1.0;
double sum = 0.0;
for (int i = 0; i < numberofterms; ++i) {
double denominator = 2.0 * i + 1.0;
double term = 4.0 / denominator;
sum = sum + sign * term;
sign = -sign;
}
estimatedValue1 = sum;
return estimatedValue1;
}
double wallisPi (int numberofterms, double &estimatedValue2)
{
double product = 1.0;
for (int i = 1; i < numberofterms; ++i) {
double r = 2.0*i;
r = r*r;
double term = r/(r-1.0);
product = product * term;
}
estimatedValue2 = 2.0 * product;
return estimatedValue2;
}
If you must use a void function, you should assign the variable passed as a parameter (estimatedV1) to the secondary variable (estimate1). Like so:
leibnizPi (nTerms, estimatedV1);
estimate1 = estimatedV1;

No, the problem is that you haven't defined your functions to return anything, and than you try to take what they return (which is undefined) and assign it to a variable, which is a mistake.
Define it as such double leibnizPi (int numberofterms, double &estimatedValue1 )
And add a return statement.
If you can't change the return type of the function, than don't try to treat it as returning a value. Just write leibnizPi (nTerms, estimatedV1); instead of estimate1 = leibnizPi (nTerms, estimatedV1);

Related

Logistic Regression Returning Wrong Prediction

I'm trying to implement logistic regression in C++, but the predictions I'm getting are not even close to what I am expecting. I'm not sure if there is an error in my understanding of logistic regression or the code.
I have reviewed the algorithms and messed with the learning rate, but the results are very inconsistent.
double theta[4] = {0,0,0,0};
double x[2][3] = {
{1,1,1},
{9,9,9},
};
double y[2] = {0,1};
//prediction data
double test_x[1][3] = {
{9,9,9},
};
int test_m = sizeof(test_x) / sizeof(test_x[0]);
int m = sizeof(x) / sizeof(x[0]);
int n = sizeof(theta) / sizeof(theta[0]);
int xn = n - 1;
struct Logistic
{
double sigmoid(double total)
{
double e = 2.71828;
double sigmoid_x = 1 / (1 + pow(e, -total));
return sigmoid_x;
}
double h(int x_row)
{
double total = theta[0] * 1;
for(int c1 = 0; c1 < xn; ++c1)
{
total += theta[c1 + 1] * x[x_row][c1];
}
double final_total = sigmoid(total);
//cout << "final total: " << final_total;
return final_total;
}
double cost()
{
double hyp;
double temp_y;
double error;
for(int c1 = 0; c1 < m; ++c1)
{
//passes row of x to h to calculate sigmoid(xi * thetai)
hyp = h(c1);
temp_y = y[c1];
error += temp_y * log(hyp) + (1 - temp_y) * log(1 - hyp);
}// 1 / m
double final_error = -.5 * error;
return final_error;
}
void gradient_descent()
{
double alpha = .01;
for(int c1 = 0; c1 < n; ++c1)
{
double error = cost();
cout << "final error: " << error << "\n";
theta[c1] = theta[c1] - alpha * error;
cout << "theta: " << c1 << " " << theta[c1] << "\n";
}
}
void train()
{
for(int epoch = 0; epoch <= 10; ++epoch)
{
gradient_descent();
cout << "epoch: " << epoch << "\n";
}
}
vector<double> predict()
{
double temp_total;
double total;
vector<double> final_total;
//hypothesis equivalent function
temp_total = theta[0] * 1;
for(int c1 = 0; c1 < test_m; ++c1)
{
for(int c2 = 0; c2 < xn; ++c2)
{
temp_total += theta[c2 + 1] * test_x[c1][c2];
}
total = sigmoid(temp_total);
//cout << "final total: " << final_total;
final_total.push_back(total);
}
return final_total;
}
};
int main()
{
Logistic test;
test.train();
vector<double> prediction = test.predict();
for(int c1 = 0; c1 < test_m; ++c1)
{
cout << "prediction: " << prediction[c1] << "\n";
}
}
start with a very small learning rate wither larger iteration number at try. Haven`t tested ur code. But I guess the cost/error/energy jumps from hump to hump.
Somewhat unrelated to your question, but rather than computing e^-total using pow, use exp instead (it's a hell of a lot faster!). Also there is no need to make the sigmoid function a member func, make it static or just a normal C func (it doesn't require any member variable from your struct).
static double sigmoid(double total)
{
return 1.0 / (1.0 + exp(-total));
}

Gaussian Curve Calculation (C++)

Given a histogram, perform a bi-means gaussian fitting.
This project fits two Gaussian curves to one histogram with an initial threshold value, and uses the curves to determine the ideal threshold value. At each iteration, the histogram is divided into 2 parts, a Gaussian is called for each part of the histogram.
My calculations must be wrong considering my resultant curve is nonsensical. Can anyone spot what's going on here? I've included my functions for calculating the biMeans Gaussian curve, the fitGauss (computes Gaussian Curve), the mean, the variance, and the Gaussian value.
int biMeanGauss (int thrVal){
double sum1, sum2, total = 0.0;
int bestThr = thrVal;
double minDiff = 99999999.0;
for (int i = thrVal; i < (maxVal-offSet); i++) {
set1DZero(GaussAry);
sum1 = fitGauss(0, i);
cout << "Sum1: " <<sum1 << endl;
sum2 = fitGauss(i, maxVal);
cout << "Sum2: " << sum2 << endl;
total = sum1 + sum2;
cout << "Total: " << total << endl;
if (total < minDiff) {
minDiff = total;
bestThr = i;
cout << "Total < MinDiff, so BestThr: " <<bestThr << endl;
}
else;
}
return bestThr;
}
double fitGauss(int leftIndex, int rightIndex){
double mean, var, sum = 0.0;
double Gval;
mean = computeMean(leftIndex, rightIndex, maxCount);
var = computeVar (leftIndex, rightIndex, mean);
for (int index = leftIndex; index <= rightIndex; index ++){
Gval = computeGaussian(histAry[index], mean, var);
sum += abs(Gval - histAry[index]);
GaussAry[index] = (int)Gval;
GaussImg[index][(int)Gval]= 1;
}
return sum;
};
double computeMean(int leftIndex, int rightIndex, int maxCount) {
int mean, n, sum = 0;
for (int i = leftIndex; i <= rightIndex; i++){
sum += (i*histAry[i]);
n++;
if (histAry[i] > maxCount){
maxCount = histAry[i];
}
}
mean = (sum / (double) n);
return mean;
}
double computeVar(int leftIndex, int rightIndex, int mean) {
double var = 0;
double sum = 0;
double n = 0;
for (int i = leftIndex; i <= rightIndex; i++) {
sum += histAry[i]*(i - mean) * (i - mean);
n++;
}
var = (sum / n);
return var;
}
double computeGaussian(int index, double mean, double var) {
double Gval = 0;
Gval = maxCount * exp(-(((index - mean)*(index - mean)) / (2 * var)));
return Gval;
}

Using codeblocks code in visual studio

I am used to write C++ project in CodeBlocks, but for some stupid reasons I have to show it to my teacher in VisualStudio. I tried to make a console app or an empty project, and copied my main file there, but with the first one I get bunch of erorrs and the second one I get 'The system cannot find the way specified'. What is different in VisualStudio? I don't understand at all what is wrong.
here is my code
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
const int kroku = 1000;
const double aa = 0; //pocatecni bod intervalu
const double bb = 1; //konečný bod intervalu
double a; //parametr
const double h = (bb - aa) / kroku; //krok
double p(double t) { //(py')' - qy = f
return exp(a*pow(t, 2));
}
double q(double t) {
return -exp(a*pow(t, 2))*pow(a, 2)*pow(t, 2);
}
double dp(double t) {
return 2 * t*a*exp(a*pow(t, 2));
}
double y[kroku + 1]; //řešení původní rce
double dydx[kroku + 1];
double z[kroku + 1]; //řešení dílčí rce
double dzdx[kroku + 1];
double x[kroku + 1]; //rozdělení intervalu (aa, bb) po krocích h
void generateX() { //generuje hodnoty x
for (int k = 0; k <= kroku; k++) {
x[k] = aa + k*h;
}
}
double partial(double pp1, double pp2, double w[kroku + 1], double dwdx[kroku + 1], double v)//řešení rce (pw')' - qw = g s pp
{
w[v] = pp1; //inicializace - počáteční podmínka
dwdx[v] = pp2; //inicialzace - počáteční podmínka
for (int i = 0; i <= kroku; i++) { //substituce dwdx proměnná -> dwdx = (w_(n+1) - w_n)/h) && dwdx =
w[i + 1] = h*dwdx[i] + w[i];
dwdx[i + 1] = (h / p(aa + h*i))*(q(aa + h*i)*w[i] - dp(aa + h*i)*dwdx[i]) + dwdx[i];
}
return 0;
}
double omega1, omega2; //nové počáteční podmínky omega1 = y(x0), omega2 = y'(x0)
void print(double N[kroku + 1])
{
fstream file;
file.open("data.dat", ios::out | ios::in | ios::trunc);//otevření/vytvoření(trunc) souboru
if (file.is_open()) //zápis do souboru
{
cout << "Writing";
file << "#" << "X" << " " << "Y" << endl;
for (int j = 0; j <= kroku; j++) {
file << x[j] << " " << N[j] << endl;
}
file << "#end";
}
else
{
cout << "Somethinq went wrong!";
}
file.close();
}
int main()
{
double alpha; //pocatecni podminka y(aa) = alpha
double beta; //y(bb) = beta
cout << "Assign the value of beta " << endl;
cin >> beta;
cout << "Assign the value of alpha " << endl;
cin >> alpha;
cout << "Assign the value of parameter a" << endl;
cin >> a;
double alpha1 = 0; //alpha1*p(aa)*y'(aa) - beta1*y(aa) = gamma1
//double alpha2 = 0; //alpha2*p(bb)*y'(bb) + beta2*y(bb) = gamma2
double beta1 = -1;
double beta2 = 1;
double gamma1 = alpha;
double gamma2 = beta;
generateX();
partial(alpha1, beta1 / p(aa), z, dzdx, aa); //(pz')'-qz = 0
omega1 = gamma2 / beta2;
omega2 = 1 / (z[kroku] * p(bb))*(gamma1 + dzdx[kroku] * p(bb));
partial(omega1, omega2, y, dydx, aa);//(py')' - qy = f = 0
print(y);
return 0;
strong text}
when I add
#include "stdafx.h"
I get four errors
2x 'Expression must have integral or unscoped enum type'
2x 'subscript is not of integral type'
for these lines
w[v] = pp1;
dwdx[v] = pp2;
Could anyone please help me? Thank you a lot
array subscript v in your line
w[v]
can not be double. It must be of interger type.

Harmonic Oscillator not getting oscillations

I am writing a harmonic oscillator program , but it does an exponential decay instead and I am not sure why. I have the code below. I use F= -k x and F = m a
I assume m = 1 and k = 1, so a = -x
So my equations to find velocity and position are
v(t) = v(t-dt) - x(t-dt) * dt
x(t) = x(t-dt) + v(t-dt) * dt
I am not sure what I am doing wrong
The code associated with this is
#include <iostream>
#include <fstream>
using namespace std;
double updateX(double intialV, double intialX, double step);
double updateV(double intialV, double intialX, double step);
int main()
{
long double position[2];long double velocity[2];
position[0] = 0.0; velocity[0] = 1.0; double time = 0.0; double step = .1;
ofstream outputFile;
outputFile.open("velo1.dat");
outputFile << time << " " << position[0] << " " << velocity[0] << "\n";
for(int i = 1; i < 50; i++)
{
time = i * step;
velocity[1] = updateV(velocity[0], position[0], step);
position[1] = updateX(velocity[0], position[0], step);
outputFile << time << " " << position[1] << " " << velocity[1] << "\n";
velocity[0] = velocity[1];
position[0] = velocity[1];
}
return 0;
outputFile.close();
}
double updateX(double intialV, double intialX, double step)
{
double stuff =(intialX + intialV * step);
return stuff;
}
double updateV(double intialV, double intialX, double step)
{
double stuff = (intialV - intialX * step) ;
return stuff;
}

Program ignoring condition?

In my code, I'm trying to prevent circles from overlapping so I specified it as a condition on the distance between the centres of the circles but it seems to not work all the time
as you can see :
could it be some kind of numerical precision rounding problem ?
Here is the relevant code (I can post the whole code if needed):
const double win_size = 800;
const double L = 50e-9; //box size (m)
const double k = 1.38e-23; // Boltzmann constant = 1.38e-23 J/K
const double R = 1.6e-10*30; //N2 radius = 1.6e-10 m
const double m = 4.65e-26; //N2 mass = 4.65e-26 kg
struct parameters{
double x;
double y;
double v_x;
double v_y;
};
bool empty_space(double x, double y, struct parameters gas[], int N, int i){
if (i == 0) return true;
for (int i = 0; i<N; i++){
if (pow(x-gas[i].x,2) + pow(y-gas[i].y,2) <= 4*R*R){
cout << gas[i].x << " " << gas[i].y << endl;
return false;
}
}
return true;
}
void initialize(struct parameters gas[], int N, double T){ // Sets initial conditions (velocity depends on temperature)
int tries = 0;
double x, y;
for (int i=0; i<N; i++){
if (tries == 10000){
cout << "Couldn't fit " << N << " molecules in the box, aborting simulation... " << endl;
exit(1);
}
x = R + (L - 2*R)*rand()/RAND_MAX;
y = R + (L - 2*R)*rand()/RAND_MAX;
if (empty_space(x,y,gas,N,i)){
gas[i].x = x;
gas[i].y = y;
}
else {
i--;
tries++;
}
gas[i].v_x = sqrt(2*k*T/m)*(1-2.0*rand()/RAND_MAX);
gas[i].v_y = (2*(rand()%2) - 1)*sqrt(2*k*T/m - pow(gas[i].v_x, 2));
}
}
void draw(int window, struct parameters gas[], int N, int automatic){
g2_pen(window,g2_ink(window,0.8,0.3,0.4));
for (int i=0; i<N; i++){
g2_circle(window,gas[i].x*win_size/L,gas[i].y*win_size/L,R*win_size/L);
}
g2_flush(window);
usleep(10000);
g2_pen(window,0);
g2_filled_rectangle(window,0,0,win_size,win_size);
if (!automatic) getchar();
}
The first debugging step is to print the coordinates of the circles that have clashed somehow, then see what the "distance" function is returning for their centers. My guess it it's somehow a rounding problem but this seems to be what you need to do next.