I am currently working out irr using algorithms through secant method. I think I am doing it correctly so far? but my main problem is that it keeps saying f is not declared in this scope:
int fx1 =f (x1);
int fx2 =f (x2);.
when i try to declare f as a function it does not allow me to, can anyone help?
#include iostream
#include iomanip
#include cmath
using namespace std;
const int Max_Iter=1000;
const double e=0.001;
double internal_r(double c, double r, int n){
double internal_r = 0.0;
for (n=1; n<=Max_Iter; n++); {
internal_r -= c/pow(1.0+r, n);
}
return internal_r;
}
int Secant(double x1, double x2, double e, double &root) {
int fx1 =f (x1);
int fx2 =f (x2);
if (x1==x2|| f(x2)==f(x1)){
root=0; return 0;
}
double x = x1 - f(x1) - (x2-x1) / (f(x2)-f(x1));
if ( fabs(f(x)) < e){
root = x; return 1;
} else {
if (f(x1)*f(x)<0){
return Secant(x1,x,e,root);
} else {
return Secant (x,x2,e,root);
}
}
}
int main() {
int n = 1;
double x1 = 0.0, x2 = 0.0, x = 0.0, fx1 = 0.0, fx2 = 0.0;
cout << "Secant Method" << endl;
cout <<"Enter first initial approximation: ";
cin >>x1;
cout <<"Enter second initial approximation: ";
cin >>x2;
cout <<"Enter the iteration number: ";
cin >>n;
if (n>=0 && n<=Max_Iter) {
cout << "you have entered an iteration sucessfully\n";
x = x1 - (fx1 * (x2 - x1)) / (fx2 - fx1);
cout <<"\n The root of the equation is "<< x <<endl;
return 0;
}
}
Related
Here is the question:
There is a house with a backyard which is square bounded by
coordinates (0,0) in the southwest to (1000,1000) in
the northeast. In this yard there are a number of water sprinklers
placed to keep the lawn soaked in the middle of the summer. However,
it might or might not be possible to cross the yard without getting
soaked and without leaving the yard?
Input The input starts with a line containing an integer 1≤n≤1000, the
number of water sprinklers. A line follows for each sprinkler,
containing three integers: the (x,y)(x,y) location of the sprinkler
(0≤x,y,≤10000) and its range r (1≤r≤1000). The sprinklers will soak
anybody passing strictly within the range of the sprinkler (i.e.,
within distance strictly less than r).
The house is located on the west side (x=0) and a path is needed to
the east side of the yard (x=1000).
Output If you can find a path through the yard, output four real
numbers, separated by spaces, rounded to two digits after the decimal
place. These should be the coordinates at which you may enter and
leave the yard, respectively. If you can enter and leave at several
places, give the results with the highest y. If there is no way to get
through the yard without getting soaked, print a line containing
“IMPOSSIBLE”.
Sample Input
3
500 500 499
0 0 999
1000 1000 200
Sample output
0.00 1000.00 1000.00 800.00
Here is my thought process:
Define circle objects with x,y,r and write a function to determine if a given point is wet or not(inside the circle or not) on the circumference is not wet btw.
class circle {
int h;
int k;
int r;
public:
circle();
circle(int h, int k, int r){
this->h = h;
this->k = k;
this->r = r;
};
bool iswet(pair<int,int>* p){
if (pow(this->r - 0.001, 2) > (pow(p->first - this->h, 2) +
pow(p->second - this->k, 2) ) ) {
return true;
}
else
return false;
};
Then implement a depth first search, prioritizing to go up and right whenever possible.
However since circles are not guaranteed to be pass on integer coordinates an the result is expected in floats with double precision (xxx.xx). So if we keep everything in integers the grid suddenly becomes 100,000 x 100,000 which is way too big. Also the time limit is 1 sec.
So I thought ok lets stick to 1000x1000 and work with floats instead. Loop over int coordinates and whenever I hit a sprinkle just snap in the perimeter of the circle since we are safe in the perimeter. But in that case could not figure out how DFS work.
Here is the latest trial
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <deque>
#include <utility>
#include <unordered_set>
#include <iomanip>
using namespace std;
const int MAXY = 1e3;
const int MAXX = 1e3;
const int MINY = 0;
const int MINX = 0;
struct pair_hash {
inline std::size_t operator()(const std::pair<int,int> & v) const {
return v.first*31+v.second;
}
};
class circle {
int h;
int k;
int r;
public:
circle();
circle(int h, int k, int r){
this->h = h;
this->k = k;
this->r = r;
};
bool iswet(pair<float,float>* p){
if (pow(this->r - 0.001, 2) > (pow(p->first - this->h, 2) + pow(p->second - this->k, 2) ) ) {
this->closest_pair(p);
return true;
}
else
return false;
};
void closest_pair(pair<float,float>* p){
float vx = p->first - this->h;
float vy = p->second - this->k;
float magv = sqrt(vx * vx + vy * vy);
p->first = this->h + vx / magv * this->r;
p->second = this->k + vy / magv * this->r;
}
};
static bool test_sprinkles(vector<circle> &sprinkles, pair<float,float>* p){
for (int k = 0; k < sprinkles.size(); k++)
if (sprinkles[k].iswet(p)) return false;
return true;
}
int main(){
int n; // number of sprinkles
while (cin >> n){
vector<circle> sprinkles_array;
sprinkles_array.reserve(n);
int h, k, r;
while (n--){
cin >> h >> k >> r;
sprinkles_array.push_back(circle(h, k, r));
}/* code */
pair<float,float> enter = make_pair(0, MAXY);
deque<pair<float,float>> mystack;
mystack.push_back(enter);
pair<float,float>* cp;
bool found = false;
unordered_set<pair<float, float>, pair_hash> visited;
while (!mystack.empty()){
cp = &mystack.back();
if (cp->first == MAXX) {
found = true;
break;
}
visited.insert(*cp);
if (cp->second > MAXY || cp->second < MINY || cp ->first < MINX ) {
visited.insert(*cp);
mystack.pop_back();
continue;
}
if (!test_sprinkles(sprinkles_array,cp)) {
continue;
}
pair<int,int> newpair = make_pair(cp->first, cp->second + 1);
if (visited.find(newpair) == visited.end()) {
mystack.push_back(newpair);
continue;
}
else visited.insert(newpair);
newpair = make_pair(cp->first + 1 , cp->second);
if (visited.find(newpair) == visited.end()) {
mystack.push_back(newpair);
continue;
}
else visited.insert(newpair);
newpair = make_pair(cp->first, cp->second - 1);
if (visited.find(newpair) == visited.end()) {
mystack.push_back(newpair);
continue;
}
else visited.insert(newpair);
newpair = make_pair(cp->first - 1, cp->second);
if (visited.find(newpair) == visited.end()) {
mystack.push_back(newpair);
continue;
}
else visited.insert(newpair);
mystack.pop_back();
}
cout << setprecision(2);
cout << fixed;
if (found){
double xin = mystack.front().first;
double yin = mystack.front().second;
pair <float, float> p = mystack.back();
p.second++;
for (int k = 0; k < sprinkles_array.size(); k++)
if (sprinkles_array[k].iswet(&p)) break;
double xout = p.first;
double yout = p.second;
cout << xin << " " << yin << " " << xout << " " << yout << endl;
}
else
{
cout << "IMPOSSIBLE" << endl;
}
}
}
Yes #JosephIreland is right. Solved it with grouping intersecting (not touching) circles. Then these groups have maxy and min y coordinates. If it exceeds the yard miny and maxy the way is blocked.
Then these groups also have upper and lower intersection points with x=0 and x=1000 lines. If the upper points are larger than the yard maxy then the maximum entry/exit points are lower entery points.
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <utility>
#include <iomanip>
using namespace std;
const int MAXY = 1e3;
const int MAXX = 1e3;
const int MINY = 0;
const int MINX = 0;
struct circle {
int h;
int k;
int r;
float maxy;
float miny;
circle();
circle(int h, int k, int r){
this->h = h;
this->k = k;
this->r = r;
this->miny = this->k - r;
this->maxy = this->k + r;
};
};
struct group {
float maxy = -1;
float miny = -1;
vector<circle*> circles;
float upper_endy = -1;
float upper_starty = -1;
float lower_endy = -1;
float lower_starty = -1;
void add_circle(circle& c){
if ((c.maxy > this->maxy) || this->circles.empty() ) this->maxy = c.maxy;
if ((c.miny < this->miny) || this->circles.empty() ) this->miny = c.miny;
this->circles.push_back(&c);
// find where it crosses x=minx and x= maxx
float root = sqrt(pow(c.r, 2) - pow(MINX - c.h, 2));
float y1 = root + c.k;
float y2 = -root + c.k;
if (y1 > this->upper_starty) this->upper_starty = y1;
if (y2 > this->lower_starty) this->lower_starty = y2;
root = sqrt(pow(c.r, 2) - pow(MAXX - c.h, 2));
y1 = root + c.k;
y2 = -root + c.k;
if (y1 > this->upper_endy) this->upper_endy = y1;
if (y2 > this->lower_endy) this->lower_endy = y2;
};
bool does_intersect(circle& c1){
for(circle* c2 : circles){
float dist = sqrt(pow(c1.h - c2->h,2)) + sqrt(pow(c1.k - c2->k,2));
(dist < (c1.r + c2->r)) ? true : false;
};
};
};
int main(){
int n; // number of sprinkles
while (cin >> n){
vector<circle> sprinkles_array;
sprinkles_array.reserve(n);
int h, k, r;
while (n--){
cin >> h >> k >> r;
sprinkles_array.push_back(circle(h, k, r));
}/* code */
vector<group> groups;
group newgroup;
newgroup.add_circle(sprinkles_array[0]);
groups.push_back(newgroup);
for (int i = 1; i < sprinkles_array.size(); i++){
bool no_group = true;
for (group g:groups){
if (g.does_intersect(sprinkles_array[i])){
g.add_circle(sprinkles_array[i]);
no_group = false;
break;
}
}
if (no_group) {
group newgroup;
newgroup.add_circle(sprinkles_array[i]);
groups.push_back(newgroup);
}
}
float entery = MAXY;
float exity = MAXY;
bool found = true;
for (group g : groups){
if ((g.miny < MINY) && (g.maxy > MAXY)){
found = false;
break;
}
if (g.upper_starty > entery)
entery = g.lower_starty;
if (g.upper_endy > exity)
exity = g.lower_endy;
}
cout << setprecision(2);
cout << fixed;
if (found){
cout << float(MINX) << " " << entery << " " << float(MAXX) << " " << exity << endl;
}
else
{
cout << "IMPOSSIBLE" << endl;
}
}
}
The following error message was received after running my code located at the end of the message:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
I'm sorry for the length of the code. It appears that the error is coming from when I am calling the numerov function within the f function. If you are able to determine what the error is would you please let me know? Thank you!
#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
using namespace std;
int nx = 500, m = 10, ni = 10;
double x1 = 0, x2 = 1, h = (x2 - x1)/nx;
int nr, nl;
vector<double> ul, q, u;
//Method to achieve the evenly spaced Simpson rule
double simpson(vector <double> y, double h)
{
int n = y.size() - 1;
double s0 = 0, s1 = 0, s2 = 0;
for (int i = 1; i < n; i += 2)
{
s0 += y.at(i);
s1 += y.at(i-1);
s2 += y.at(i+1);
}
double s = (s1 + 4*s0 + s2)/3;
//Add the last slice separately for an even n+1
if ((n+1)%2 == 0)
return h*(s + (5*y.at(n) + 8*y.at(n-1) - y.at(n-2))/12);
else
return h*2;
}
//Method to perform the Numerov integration
vector <double> numerov(int m, double h, double u0, double u1, double q)
{
vector<double> u;
u.push_back(u0);
u.push_back(u1);
double g = h*h/12;
for (int i = 1; i < m+1; i++)
{
double c0 = 1 + g*q;
double c1 = 2 - 10*g*q;
double c2 = 1 + g*q;
double d = g*(0);
u.push_back((c1*u.at(i) - c0*u.at(i-1) + d)/c2);
}
return u;
}
//Method to provide the function for the root search
double f(double x)
{
vector<double> w;
vector<double> j = numerov(nx + 1, h, 0.0, 0.001, x);
for (int i = 0; i < 0; i++)
{
w.push_back(j.at(i));
}
return w.at(0);
}
//Method to carry out the secant search
double secant(int n, double del, double x, double dx)
{
int k = 0;
double x1 = x + dx;
while ((abs(dx) > del) && (k < n))
{
double d = f(x1) - f(x);
double x2 = x1 - f(x1)*(x1 - x)/d;
x = x1;
x1 = x2;
dx = x1 - x;
k++;
}
if (k == n)
cout << "Convergence not found after " << n << " iterations." << endl;
return x1;
}
int main()
{
double del = 1e-6, e = 0, de = 0.1;
//Find the eigenvalue via the secant method
e = secant (ni, del, e, de);
//Find the solution u(x)
u = numerov(nx + 1, h, 0.0, 0.01, e);
//Output the wavefunction to a file
ofstream myfile ("Problem 2.txt");
if (myfile.is_open())
{
myfile << "Input" << "\t" << "u(x)" << endl;
double x = x1;
double mh = m*h;
for (int i = 0; i <= nx; i += m)
{
myfile << x << "\t" << u.at(i) << endl;
x += mh;
}
myfile.close();
}
return 0;
}
vector<double> w;
for (int i = 0; i < 0; i++)
{
w.push_back(j.at(i));
}
return w.at(0);
w will have nothing in it, since that loop will run 0 times. Thus, w.at(0) will throw the out of range error.
Why do you think the problem is in the numerov function?
I see an error in the function f?
vector<double> w;
vector<double> j = numerov(nx + 1, h, 0.0, 0.001, x);
for (int i = 0; i < 0; i++)
{
w.push_back(j.at(i));
}
return w.at(0);
There is nothing on vector w and you try to access element 0.
I am doing a former assignment in C++ and trying to figure out how to get correct ASCII X-Y plot.
So what's really happening is that user is given a menu which allows them to choose a particular trig function.All of the functions have range between [-4..6] for X and [-12...5] for Y.Next user will be allowed to select amount of graduations(or values between the restricted x and y range] and if they want to see resultant values or Bitmap.The final output will be in values/bitmap.I have pasted wolfram alpha link for the functions in comments.
What I have done is incremented each column in 2D output by product of 1/(graduation-1)(i.e. 1/3 if graduated value is 4) and column #.Once that product reaches 1,I am not getting correct output for the values.
#include <iostream>
#include <cmath>
using namespace std;
double minX=-4;
double maxX=6;
double minY=-12;
double maxY=5;
void displayValues(double result[],int result_size,int graduationVal,double percentIncrease,int menuSelection){
int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;
int k=0;
int i=0;
int division=0;
//Add Values into array until result-1 values
while(i < result_size){
//cout<<"Before j";
//Calculate all the horizontal axis values
for(int j=0; j< graduationVal;j++){
if(displaySelection==1){
//cout<<"In if";
if(menuSelection==1){
result[i]=sin(minX+(percentIncrease*j))*cos(minY+(percentIncrease*k));
cout<<"\n Increase in value of x by "<<percentIncrease*j<<" ";
cout<<"Increase in value of y by "<<percentIncrease*k<<"\n";
//cout<<sin(minX+(percentIncrease*j))<<"\n";
//cout<<cos(minY+(percentIncrease*k))<<"\n";
cout<<result[i]<<" ";
}else if(menuSelection==2){
result[i]=sin(minX+(percentIncrease*j))+pow(cos(minY+(percentIncrease*j)),2)-(minX+(percentIncrease*j))/(minY+(percentIncrease*k));
cout<<"\n Increase in value of x by "<<percentIncrease*j<<" ";
cout<<"Increase in value of y by "<<percentIncrease*k<<"\n";
cout<<result[i]<<" ";
}else if(menuSelection==3){
result[i]=(0.5 * sin(minX+(percentIncrease*j)))+(0.5 *cos(minY+(percentIncrease*k)));
cout<<"\n Increase in value of x by "<<percentIncrease*j<<" ";
cout<<"Increase in value of y by "<<percentIncrease*k<<"\n";
cout<<result[i]<<" ";
}else if(menuSelection==4){
result[i]=(0.5 * sin(minX+(percentIncrease*j)))+(minX+(percentIncrease*j)) * cos(3 * (minY+(percentIncrease*k)));
cout<<result[i]<<" ";
}
//cout<<"J is"<<j<<"\n";
//cout<<"K is"<<k<<"\n";
//cout<<"I is"<<i<<"\n";
}else{
if(menuSelection==1){
result[i]=sin(minX+(percentIncrease*j))*cos(minY+(percentIncrease*k));
cout<<((result[i] > 0 )?"O":"X");
}else if(menuSelection==2){
result[i]=sin(minX+(percentIncrease*j))+pow(cos(minY+(percentIncrease*j)),2)-(minX+(percentIncrease*j))/(minY+(percentIncrease*k));
cout<<((result[i] > 0 )?"O":"X");
}else if(menuSelection==3){
result[i]=(0.5 * sin(minX+(percentIncrease*j)))+(0.5 *cos(minY+(percentIncrease*k)));
cout<<((result[i] > 0 )?"O":"X");
}else if(menuSelection==4){
result[i]=(0.5 * sin(minX+(percentIncrease*j)))+(minX+(percentIncrease*j)) * cos(3 * (minY+(percentIncrease*k)));
cout<<((result[i] > 0 )?"O":"X");
}
}//End display choice if
//Increment Array Index
i++;
//cout<<"Bottom of j";
}//End of j loop
cout<<"\n";
//Increment y-values
if(k<graduationVal){
k++;
}
}//End of While
}
int main(){
int menuChoice=-1;
int displaychoice=0;
double distanceFromMinMaxX=4+6;
double distanceFromMinMaxY=12+5;
int graduations=0;
// double precisionX;
// double precisionY;
double pctIncrease;
while(menuChoice!=0){
cerr<<"Select your function\n";
cerr<<"1. sin(x)cos(y)\n";
cerr<<"2. sin(x)+cos^2(x)-x/y\n";
cerr<<"3. 1/2 sin(x) + 1/2 cos(y)\n";
cerr<<"4. 1/2 sin(x) + xcos(3y)\n";
cerr<<"0. Quit\n";
cin>>menuChoice;
if(menuChoice == 0){
return 0;
}
cerr<<"Number of graduations per axis: ";
cin>>graduations;
pctIncrease=1/(double)(graduations - 1);
int values_size=graduations * graduations;
double values[values_size];
/*int yValues[graduationVal];*/
// precisionX=distanceFromMinMaxX/graduations;
// precisionY=distanceFromMinMaxY/graduations;
displayValues(values,values_size,graduations,pctIncrease,menuChoice);
}
}
Edit:
#include <iostream>
#include <cmath>
using namespace std;
double minX=-4;
double maxX=6;
double minY=-12;
double maxY=5;
double* calculateValues(double val[],int val_size,int graduationVal,double xPrecision,double yPrecision,int menuSelection){
/*int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;*/
int k=0;
int i=0;
//Add Values into array until result-1 values
while(i < val_size){
for(int j=0; j<graduationVal;j++){
if(menuSelection==1){
val[i]=sin(minX+(xPrecision*j))*cos(minY+(yPrecision*k));
}else if(menuSelection==2){
val[i]=sin(minX+(xPrecision*j))+pow(cos(minY+(xPrecision*j)),2)-(minX+(xPrecision*j))/(minY+(yPrecision*k));
}else if(menuSelection==3){
val[i]=(0.5 * sin(minX+(xPrecision*j)))+(0.5 *cos(minY+(yPrecision*k)));
}else if(menuSelection==4){
val[i]=(0.5 * sin(minX+(xPrecision*j)))+(minX+(xPrecision*j)) * cos(3 * (minY+(yPrecision*k)));
}
//Increment Array Index
i++;
}//End of j loop
//Increment y-values
if(k<graduationVal){
k++;
}
}//End of While
return val;
}
void displayValues(double result[],int result_size,int numOfGraduations){
int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;
int k=0;
int i=0;
while(i< result_size){
for(int j=0;j<numOfGraduations;j++){
if(displaySelection==1){
cout<<result[i]<<" ";
}else{
cout<<((result[i] > 0 )?"O":"X");
}
i++;
}
cout<<"\n";
}
}
int main(){
int menuChoice=-1;
int displaychoice=0;
double distanceFromMinMaxX=4+6;
double distanceFromMinMaxY=12+5;
int graduations=0;
double precisionX;
double precisionY;
double pctIncrease;
while(menuChoice!=0){
cerr<<"Select your function\n";
cerr<<"1. sin(x)cos(y)\n";
cerr<<"2. sin(x)+cos^2(x)-x/y\n";
cerr<<"3. 1/2 sin(x) + 1/2 cos(y)\n";
cerr<<"4. 1/2 sin(x) + xcos(3y)\n";
cerr<<"0. Quit\n";
cin>>menuChoice;
if(menuChoice == 0){
return 0;
}
cerr<<"Number of graduations per axis: ";
cin>>graduations;
pctIncrease=1/(double)(graduations - 1);
int values_size=graduations * graduations;
double values[values_size];
/*int yValues[graduationVal];*/
precisionX=distanceFromMinMaxX/graduations;
precisionY=distanceFromMinMaxY/graduations;
/*cout << "# of graduations: " << graduations << endl;
cout << "Precision: "<< endl;
cout << "x: " << precisionX << endl;
cout << "y: " << precisionY << endl;*/
calculateValues(values,values_size,graduations,precisionX,precisionY,menuChoice);
displayValues(values,values_size,graduations);
}
}
Edit:I am using gcc
This produces output similar to the screencap you linked (where the user chose option 2). The TextPlot2d function takes a lambda or functor which calculates the desired function, as well as two PlotRange structs for specifying how the x and y axes should be scaled. I also used different output characters because I had a hard time distinguishing 'X' vs. 'O'.
#include <iostream>
#include <cmath>
struct PlotRange {
double begin, end, count;
double get_step() const { return (end - begin) / count; }
};
template <typename F>
void TextPlot2d(F func, PlotRange range_x, PlotRange range_y) {
const auto step_x = range_x.get_step();
const auto step_y = range_y.get_step();
// multiply steps by iterated integer
// to avoid accumulation of error in x and y
for(int j = 0;; ++j) {
auto y = range_y.begin + step_y * j;
if(y >= range_y.end) break;
for(int i = 0;; ++i) {
auto x = range_x.begin + step_x * i;
if(x >= range_x.end) break;
auto z = func(x, y);
if(z != z) { std::cout << '?'; } // NaN outputs a '?'
else { std::cout << (z < 0 ? '#':'o'); }
}
std::cout << '\n';
}
}
int main() {
TextPlot2d(
[](double x, double y){ return std::sin(x) + std::cos(y/2)*std::cos(y/2) - x/y; },
{-4.0, 6.0, 40.0},
{-12.0, 5.0, 40.0}
);
}
Tada!
ooooooo######ooooooooooooooooooooooooooo
oooooo#######ooooooooooooooooooooooooooo
ooooo#########oooooooooooooooooooooooooo
oooo###########ooooooooooooooooo######oo
ooo#############ooooooooooooooo#######oo
ooo#############ooooooooooooooo########o
oo##############ooooooooooooooo########o
ooo#############ooooooooooooooo########o
ooo#############oooooooooooooooo######oo
oooo###########oooooooooooooooooo####ooo
ooooo#########oooooooooooooooooooooooooo
ooooo#########oooooooooooooooooooooooooo
oooooo#######ooooooooooooooooooooooooooo
ooooooo######ooooooooooooooooooooooooooo
oooooo#######ooooooooooooooooooooooooooo
oooooo#######ooooooooooooooooooooooooooo
ooooo#########oooooooooooooooooooooooooo
ooo############ooooooooooooooooooooooooo
oo#############ooooooooooooooooooooooooo
################oooooooooooooooooooooooo
################oooooooooooooooooooooooo
################oooooooooooooooooooooooo
################oooooooooooooooooooooooo
################oooooooooooooooooooooooo
###############ooooooooooooooooooooooooo
###############ooooooooooooooooooooooooo
###############ooooooooooooooooooooooooo
###############ooooooooooooooooooooooooo
################oooooooooooooooooooooooo
oooooooooooooooooo######################
oooooooooooooooooooooo##################
oooooooooooooooooooooooo################
ooooooooooooooooooooooooo###############
ooooooooooo###ooooooooooo###############
ooooooooo#######ooooooooo###############
oooooooo########oooooooooo##############
ooooooo#########oooooooooo##############
ooooooo#########ooooooooooo#############
ooooooo########oooooooooooo#############
oooooooo######oooooooooooooo############
I finally got the output!!Appearantly function#2 was wrong and that's why I wasn't getting correct answer.
#include <iostream>
#include <cmath>
using namespace std;
double minX=-4;
double maxX=6;
double minY=-12;
double maxY=5;
void calculateValues(double val[],int val_size,int graduationVal,double xPrecision,double yPrecision,int menuSelection){
/*int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;*/
//double val[];
int k=0;
int i=0;
//Add Values into array until result-1 values
while(i < val_size){
for(int j=0; j<graduationVal;j++){
if(menuSelection==1){
val[i]=sin(minX+(xPrecision*j))*cos(minY+(yPrecision*k));
}else if(menuSelection==2){
val[i]=sin(minX+(xPrecision*j))+pow(cos((minY+(yPrecision*k))/2),2)-(minX+(xPrecision*j))/(minY+(yPrecision*k));
}else if(menuSelection==3){
val[i]=(0.5 * sin(minX+(xPrecision*j)))+(0.5 *cos(minY+(yPrecision*k)));
}else if(menuSelection==4){
val[i]=(0.5 * sin(minX+(xPrecision*j)))+(minX+(xPrecision*j)) * cos(3 * (minY+(yPrecision*k)));
}
//Go to next value in array
i++;
}//End of j loop
//Increment y-values
if(k<graduationVal){
k++;
}
}//End of While
}
void displayValues(double result[],int result_size,int numOfGraduations){
int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;
int k=0;
int i=0;
while(i< result_size){
for(int j=0;j<numOfGraduations;j++){
if(displaySelection==1){
cout<<result[i]<<" ";
}else{
cout<<((result[i] > 0 )?"O":"#");
}
i++;
}
cout<<"\n";
}
}
int main(){
int menuChoice=-1;
int displaychoice=0;
double distanceFromMinMaxX=maxX-minX;
double distanceFromMinMaxY=maxY-minY;
int graduations=0;
double precisionX;
double precisionY;
double pctIncrease;
while(menuChoice!=0){
cerr<<"Select your function\n";
cerr<<"1. sin(x)cos(y)\n";
cerr<<"2. sin(x)+cos^2(y/2)-x/y\n";
cerr<<"3. 1/2 sin(x) + 1/2 cos(y)\n";
cerr<<"4. 1/2 sin(x) + xcos(3y)\n";
cerr<<"0. Quit\n";
cin>>menuChoice;
if(menuChoice == 0){
return 0;
}
cerr<<"Number of graduations per axis: ";
cin>>graduations;
//pctIncrease=1/(double)(graduations - 1);
int values_size=graduations * graduations;
double values[values_size];
/*int yValues[graduationVal];*/
precisionX=(distanceFromMinMaxX)/graduations;
precisionY=(distanceFromMinMaxY)/graduations;
/*cout << "# of graduations: " << graduations << endl;
cout << "Precision: "<< endl;
cout << "x: " << precisionX << endl;
cout << "y: " << precisionY << endl;*/
calculateValues(values,values_size,graduations,precisionX,precisionY,menuChoice);
displayValues(values,values_size,graduations);
}
}
I am new to programming and am trying to implement A star search algorithm on C++. I am having segmentation fault:11 because of not initializing my pointer. I have tried it several different ways to no avail.
I am still confused about the whole pointer and dynamic memory allocation concept.
Can anyone help me figure it out? Thank you.
#include <iostream>
#include <vector>
#include <fstream>
#include <math.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
// Definition of the heuristic. The heuristic in this problem is the distance between
// two coordinates
double heuristic(double x1, double y1, double x2, double y2) {
double dx, dy;
dx = x1 - x2;
dy = y1 - y2;
return sqrt(dx*dx - dy*dy);
//return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2));
}
// ----- A Star Search Algorithm (f = g + h)----
double** a_star_search(double points[][2]) {
int count = 1;
double** points1 = NULL;
// points1[10][2];
double x1 = points[0][0];
double y1 = points[0][1];
points1[count - 1][0] = x1;
points1[count - 1][1] = y1;
while (count <= 10) {
double tempx1;
double tempy1;
double distance = 10000000;
for (int i = 0; i < 10; i++) {
if (points[i][0] != 0 && points[i][1] != 0) {
double distance2 = heuristic(x1, y1, points[i][0], points[i][1]);
if (distance2 < distance) {
tempx1 = points[i][0];
tempy1 = points[i][1];
distance = distance2;
}
}
}
x1 = tempx1;
y1 = tempy1;
count++;
points1[count - 1][0] = x1;
points1[count - 1][1] = y1;
}
return points1;
}
int main() {
double points[7][2];
int counter = 0;
ifstream infile("waypoints.txt");
int a, b;
while (infile >> a >> b)
{
points[counter][0] = a;
points[counter][1] = b;
counter++;
}
points[6][0] = points[0][0];
points[6][1] = points[0][1];
double** points1 = a_star_search(points);
cout << "Initial Sequence: ";
for (int i = 0;i < 7;i++) {
cout << "(" <<points[i][0] << " , " << points[i][1] << "), ";
}
cout << "\n\nOptimized Sequence: ";
for (int i = 0;i < 7;i++) {
cout << "(" << points1[i][0] << " , " << points1[i][1] << "), ";
}
cout << "\n\nTotal Distance after A* search: ";
double totaldistance = 0;
for (int i = 0;i < 6;i++) {
double dis = heuristic(points1[i][0], points1[i][1], points1[i + 1][0], points1[i + 1][1]);
cout << dis << "+";
totaldistance = totaldistance + dis;
}
cout<< "=" << totaldistance <<endl;
}
You are not allocating memory dynamically for double** points1 variable after setting it to NULL in your a_star_search function. As pointed out by #user4581301, use std::vector. This will simplify your code significantly and worth spending the time to learn STL containers.
I am trying to print out the variable *loan_Amt* when the monthly payment exceeds/is equal to the 30% amount that is found in the *monthly_payment* function. This is my first attempt at writing a c++ program with functions!
#include<iostream>
#include<conio.h>
#include<string>
#include<iomanip>
#include<math.h>
using namespace std;
double monthly_Payment (double amt_Amt)
{
double r;
r = ( amt_Amt/ 12) * 30/100;
return (r);
}
double interest_Calculate(double interest_Amt)
{
double r;
r = (interest_Amt * .010);
return (r);
}
//double loan_Calculate()
//{
//int x = interest_Calculate(interest_Rate);
//double monthly = (loan_Amt * x) / (1 - pow(1.0 + i,-(12*30)));
//for (((int loan_Amt = 20000) * (x/12)) / pow(1.0 + i,-(12*30)); loan_Amt>0; loan_Amt++);
//}
int main()
{
double gross_Salary;
double interest_Rate;
int x;
int i;
double monthly;
std::cout << "Please enter your yearly gross salary:";
std::cin >> gross_Salary;
std::cout << "Please enter an interest rate:";
std::cin >> interest_Rate;
int z;
z = monthly_Payment (gross_Salary);
std::cout << "The target (30 percent of monthly salary) monthly payment range is:" << z;
for ( int loan_Amt = 0; loan_Amt <= 5000000; x++ ) {
do {
x = interest_Calculate(interest_Rate);
monthly = (loan_Amt * x) / (1 - pow(1.0 + x,-(12*30)));
std::cout << loan_Amt;
} while (monthly >= z );
}
getch();
return 0;
}
The for loop has problem, I think,
for ( int loan_Amt = 0; loan_Amt <= 5000000; x++ ) {
do {
x = interest_Calculate(interest_Rate);
monthly = (loan_Amt * x) / (1 - pow(1.0 + x,-(12*30)));
std::cout << loan_Amt;
} while (monthly >= z );
}
loan_Amt will never change its value, so this is an infinite loop.
This line in the do-while loop,
std::cout << loan_Amt;
will always print zero