Odd function pointer segmentation fault [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 1 year ago.
Improve this question
I have to find the value of x such that f(x)=C, where f is a monotonically increasing function over the interval [a,b]. It has to have a logarithmic complexity so I've made this function which I believe to be correct:
double search(double a, double b, double c, double (*f)(double x)) {
double pivot;
do {
pivot = abs((a-b)/2);
if (abs((*f)(pivot) - c) < 0.001) { //f(x) == c
return pivot;
} else if ((*f)(pivot) > c) {
b = pivot;
} else {
a = pivot;
}
} while (abs(a-b) != 0);
return 0;
}
which works whenever I call it like this:
int main(void) {
double a = 0.0, b = 10.0, c = 5.0;
cout << search(a, b, c, func1) << endl;
return 0;
}
but if I change it to this (the value of b):
int main(void) {
double a = 0.0, b = 100.0, c = 5.0;
cout << search(a, b, c, func1) << endl;
return 0;
}
I get a segmentation fault when the function is called. What is going wrong here?
(I can see that the program crashes when the function is called when I use the VSCode debugger. Otherwise, when I just compile and run it, it seems to get stuck in an infinite loop or something i.e. it doesn't throw the segmentation fault error).
If needed, func1 simply does return 2 * x.
EDIT:
Here's the full .cpp file if someone needs it to reproduce:
#include <iostream>
using namespace std;
double func1(double x) {
return 2 * x;
}
double func2(double x) {
return x + 0.5;
}
double search(double a, double b, double c, double (*f)(double x)) {
double pivot;
do {
pivot = abs((b-a)/2);
if (abs((*f)(pivot) - c) < 0.1) { //f(x) == c
return pivot;
} else if ((*f)(pivot) > c) {
b = pivot;
} else {
a = pivot;
}
} while (abs(b-a) != 0);
return 0;
}
int main(void) {
double a = 0.0, b = 10.0, c = 5.0;
cout << search(a, b, c, &func1) << endl;
cout << search(a, b, c, func1) << endl;
return 0;
}
where changing the value of b to 100.0 will cause the fault to occur.

pivot = abs((a-b)/2); is wrong it as it computes half of the distance from a to b not the middle point of them, use:
pivot = abs((a-b)/2)+a; // provided that *a* is less than *b*

Related

cout does not name a type despite wrapped functions and namespace std [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am getting the error 'cout does not name a type' (line 36 ie main function) along with a couple of other errors in main().
All code is wrapped well within the functions and I have used
using namespace std;
but I am still getting this error along with other ~identifier~ was not declared in this scope errors in the main function.
Code:
#include<iostream>
#include<cmath>
using namespace std;
double discriminant (double a, double b, double c){
return (pow(b,2) - (4 * a * c));
}
double* compute_roots(double a, double b, double c){
double* x;
double x1,x2;
double d = discriminant(a,b,c);
if (d>0){
cout<<"Two real roots"<<endl;
}
else if (d=0){
cout<<"One unique solution"<<endl;
}
else
{
cout<<"Does not support complex roots";
//throw "Negative roots!";
return x;
}
x1 = (-b + sqrt(d))/(2*a);
x2 = (-b - sqrt(d))/(2*a);
x[0] = x1;
x[1] = x2;
return x;
}
int main{
double a=2.0,b=5,c=3.1;
double* res=compute_roots(a,b,c);
cout<<res[0];
cout<<res[1];
return 0;
}
int main{
That should be
int main() {
Otherwise the compiler thinks you're trying to define an integer variable called main, not a function, and will get very confused by the code that follows.
Also, compute_roots never initializes its local variable x before using its value, so that can't work:
double* x;
// ...
return x;
Another problem:
else if (d=0){
should probably be d == 0 (= is for assignment, not comparison).
the main function misses (). and you are using d = 0 as the condition for else if not an error but it is not what you want. you also have memory leak.
this is probably what you need:
#include<iostream>
#include<cmath>
#include <memory>
using namespace std;
double discriminant(double a, double b, double c) {
return (pow(b, 2) - (4 * a * c));
}
void deleter(double* x) {
delete[] x;
}
shared_ptr<double> compute_roots(double a, double b, double c) {
shared_ptr<double> x;
x.reset(new double[2], deleter);
double x1, x2;
double d = discriminant(a, b, c);
if (d > 0) {
cout << "Two real roots" << endl;
}
else if (d == 0) {
cout << "One unique solution" << endl;
}
else
{
cout << "Does not support complex roots";
//throw "Negative roots!";
return x;
}
x1 = (-b + sqrt(d)) / (2 * a);
x2 = (-b - sqrt(d)) / (2 * a);
x.get()[0] = x1;
x.get()[1] = x2;
return x;
}
int main() {
double a = 2.0, b = 5, c = 3.1;
shared_ptr<double> res = compute_roots(a, b, c);
cout << res.get()[0];
cout << res.get()[1];
return 0;
}

C++ equation returns -nan(ind)

So I'm writing code to semi-automatically solve (in)direct proportional questions using two values that are always given at the start. It's returning a -nan(ind) error so I'm hopefully seeking for someone to help. Thank you in advance, your help is always appreciated no matter how small it is.
I understand nan is not a number but it's just being irritating to fix this, not asking for someone to feed me the fix but if you'd like to you may - I'm looking to find a fix so that in the future I wouldn't be as clueless when it comes to an issue like this.
#include "Prop.h"
float c, d, k;
std::string prop::getinput(std::string obj) {
std::getline(std::cin, obj);
}
float prop::storefloat(float inp) {
std::cin >> inp;
return 1;
}
int prop::printarr(float arr[]) {
std::copy(arr, arr + sizeof(arr) / sizeof(arr[0]), std::ostream_iterator<float>(std::cout, "\n"));
}
int prop::compare(int com, int pare) {
if (com && pare <= 0) {
return 0;
}
}
void prop::direct(float a, float b, float constant) {
constant = DIRECTfindconstant(a, b);
printf("%d\n", constant);
c = ((constant) * (b));
printf("%d\n", c);
d = ((b) / (constant));
printf("%d\n", d);
std::cout << "Constant : " << constant << "\nDominant algebraic letter : " << c << "\nSecond Letter : " << d << "\n";
}
float prop::completedirect(float a, float b, float c) {
compare(a, b);
direct(a, b, c);
return 0;
}
float prop::DIRECTfindconstant(float a, float b) {
//k on bottom right, a ontop, b on bottom right
float k = ((a) / (b));
return k;
}
float prop::INDIRECTfindconstant(float a, float b) {
//k ontop, a on bottom left, b on bottom right
float k = a * b;
return k;
}
void prop::caseinput(int inp, float val, float val2) {
switch (inp) {
case Prop::proportionality::direct: {
float constant = DIRECTfindconstant(val, val2);
printf("%d\n", constant);
printf("%d", val);
printf("%d", val2);
completedirect(val, val2, constant);
break;
};
default:
break;
}
}
//prop.cpp
int main()
{
std::cin >> test;
pro->storefloat(a);
pro->storefloat(b);
pro->caseinput(test, a, b);
system("pause");
return 0;
}
Quoting the relevant part:
float prop::storefloat(float inp) {
std::cin >> inp;
return 1;
}
This is pass-by-value, as your book should tell you. You can change the local inp, but it does not affect the caller. The return value 1 is pointless here, while return values are the logical way to return a value to the caller.

My C++ program has trouble calculating this series for Euler's number

Here is the C++ program i wrote to solve the above series:
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int factorial(int a)
{
if (a > 1)
return a * factorial(a - 1);
else
return 1;
}
float series(float x, int n, float b)
{
if (abs(pow(x, n) / factorial(n)) < pow(10, -6) || abs(pow(x, n) / factorial(n)) == pow(10, -6)) { return b; }
else return b = (pow(x, n) / factorial(n)) + series(x, n + 1, b);
}
int main()
{
float x;
cout << "Enter x: "<<endl;
cin >> x;
cout << "E^x = " << series(x,0,0);
system("pause");
return 0;
}
It works fine when abs(x) < 2 but when abs(x) >= 2 this error appears:
Unhandled exception at 0x00F02539 in 33b.exe: 0xC00000FD: Stack
overflow (parameters: 0x00000001, 0x00F22FF8). occurred
I want to know why does this happen and how can i fix it?
Your problem is too deep recursion. Consider loop instead.
float series(float x)
{
const float epsilon = 1e-6f;
double error = 1;
double res = 1.f;
int iter = 1;
while (abs(error) > epsilon) {
error *= (x / iter++);
res += error;
cout << error << endl;
}
return res;
}
int main()
{
cout << "E^x = " << series(3);
system("pause");
return 0;
}
To be clearer about what happens:
When you call a function inside another function, the context of the parent function is saved to make room for the new context. When you make millions of inception, the memory stack in charge to save these context is full and overflows.
This is a Stack Overflow.
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int factorial[200];
int Factorial(int a)
{ if(a>0){
factorial[a]=a * factorial[a-1];
return factorial[a];
}
else
factorial[a]=1;
return 1;
}
double series(double x, int n, double b)
{ double temp=(abs(pow(x, n)) / Factorial(n));
if (temp <= 0.000001) { return b; }
else return (temp + series(x, n + 1, b));
}
int main()
{
float x;
cout << "Enter x: "<<endl;
cin >> x;
cout << "E^x = " << series(x,0,0);
system("pause");
return 0;
}
umm this solution is working. all i did was i took your code removed abs(pow(x, n) / factorial(n)) wherever its repeating and intialised to a new variable temp. then instead of < || == u can directly put <=. and rather than invoking a a function to calculate .000001 every time you could just give that value to reduce time further. however i believe that the reason why the code may not have worked is too much recursion. so for factorials i used dynamic programming to reduce its complexity. the above code is working perfectly fine.

VS2017 "non-standard syntax; use '&' to create a pointer to member " [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
class DefInt
{
private:
double a;
double b;
double (*f)(double x);
int N;
public:
DefInt(double c, double d, double (*g)(double y))
{
a = c;
b = d;
f = g;
}
double BySimpson()
{
double sum = f(a) + 4 * f((a + b) / 2) + f(b);
return sum * (b - a) / 3;
}
};
double g(double y)
{
double sum = 1 - y * y + y * y * y;
return sum;
}
int main()
{
int c = 1;
int d = 2;
double y;
DefInt MyInt(c, d, g);
cout << "BySimpson:" << MyInt.BySimpson << endl << endl;
system("pause");
return 0;
}
why is there a error saying 'DefInt::BySimpson': non-standard syntax; use '&' to create a pointer to member?
By the way I ommited a similar DefInt member function,though it is nearly the same as Bysimpson, it works fine and no error occurs. I do not understand why.
I have attched it here.
double ByTrapzold(int n)
{
N = n;
double sum = f(a + (b - a) / N);
for (int i = 2; i <= N; i++)
{
sum = sum + 2 * f(a + (b - a) * i / N);
}
sum = sum + f(a + (b - a) * (N + 1) / N);
return sum * (b - a) / (2 * N);
}
Thanks.
On the line
cout << "BySimpson:" << MyInt.BySimpson << endl << endl;
You probably meant to make a call to BySimpson but your forgot the ()
cout << "BySimpson:" << MyInt.BySimpson() << endl << endl;
The reason you get this misleading error is because pre ISO standarization MyInt.BySimpson would actually mean you wanted the address just like for normal function the function name on its own gives the address of the function. Later however the use of & to take the address of a member was put in the standard as a requirement. So Visual Studio thinks you are still using the old syntax and wants you to use the new syntax.

How to find square root with 20 digit precision in C++?

Hi guys I'm stuck with this homework where I need to find the root of equation using Bisection method with precision 10^-20 aka 0.00000000000000000001 so at first I though it was cause I wasn't using long double and also L at the end of the numbers, however even when I use it my last 3 digits are not correct, for the code that is given below ask you to give the number for a in my case is 5 , so I get 2.3227751229355622087
while the correct answer should be 2.3227751229355622988, I really can't find my mistake , will be happy if some1 assist me with this problem.
For your reference, here's a description and illustration of the Bisection method.
Here's my code:
#include<iostream>
#include<cmath>
#include<math.h>
#include<iomanip>
using namespace std;
long double f(long double x, long double a);
long double F = 123456L % 100L;
long double f(long double x, long double a)
{
long double sum = pow(x, 5) - a*x - F;
return sum;
}
int main()
{
cout.setf(ios::fixed);
long double a, b, c, fa, fb, fc;
long double e;
long double aa;
bool flag = true;
while (cin >> aa)
{
cout.precision(19);
flag = true;
a = 0L;
b = 10L;
e = 0.00000000000000000001L;
if (f(a, aa)*f(b, aa)>0)
{
flag = false;
}
while(fabs(a-b)>=e){
c = (a + b) / 2.0L;
fa = f(a, aa);
fb = f(b, aa);
fc = f(c, aa);
if (fc == 0)
{
break;
}
if (fa*fc>0)
{
a = c;
}
else if (fa*fc<0)
{
b = c;
}
}
if (flag == true)
{
cout << c << endl;
}
else
{
cout << "NO SOLUTION" << endl;
}
}
return 0;
}
The problem was that I was using the wrong compiler (Visual Studio).
As soon as installed another compiler, there wasn't any problem with the 20 digit precision. As I investigated more, it appears that some compilers have a limit after the decimal to 14 or 15.
If c++ refuses to round your number to higher precision change the compiler :)