c++ return two arrays from the function - c++

I find a solution to the equation using the bisection method.
And I need to find the value of a and b on some iterations. Therefore, I made two arrays for these points, respectively.
in order to "pull out" the number of iterations from the function, I had no problems. They are displayed on the screen. But how do I "pull out" these two arrays?Please tell me how to do it. Thank you in advance!
double f1(double x){
return x*x-5*sin(x);
}
double f2(double x){
return exp(x)-pow(10,x);
}
double f3(double x){
return sin(x)-x+0.15;
}
double f4(double x){
return x-pow(9+x,0.5)+x*x-4;
}
double dihotom (double a , double b , double e , double(*fp)(double),int &iter,double &points_a[],double &points_b[]){
double c , fc , fa = fp(a);
iter=(log10((b-a)/e))/log10(2);
int step = iter/3;
int step_current = step;
int it=0;
int k=0;
do{
c=(a+b)/2;
fc=fp(c);
if (fa*fc<=0) b = c ; else a = c;
it++;
if(it==step_current){
points_a[k]=a;
points_b[k]=b;
k++;
step_current=step_current+step;
}
fa=fp(a);
printf ("it %d: a = %lf,b = %lf\n",iter,a,b);
}while (fabs(a-b)>=e);
return c;
}
int main(int argc, char *argv[]) {
int int_s=0;
double points_a[3];
double points_b[3];
double k3= dihotom (0.5,1,0.0001,f3,int_s,points_a[3],points_b[3]);
printf("For F3 - root = %lf, F3(%.2lf)=%lf ;iter =%d\n", k3, k3 ,f3(k3),int_s);
int i=0;
for(i=0;i<3;i++){
printf("step : %d , a: %lf, b: %lf ", i,points_a[i],points_b[i]);
}
return 0;
}

In your case, you should take the arrays by reference:
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double (&points_a)[3], double (&points_b)[3]) {
// ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
You could also let the arrays decay into pointers:
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double points_a[], double points_b[]) {
or
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double* points_a, double* points_b) {
But by taking them by reference, you make sure that you only accept arrays of the correct size.
In either case, the call to the function will simply be:
double k3 = dihotom(0.5, 1, 0.0001, f3, int_s, points_a, points_b);
Demo

If you want to return two arrays from a function then make a struct with two vectors. Something like this. The way you are doing it is harder to maintain, who will allocate the arrays and delete them for example?
// todo for you : create better names then points_a and points_b
struct my_result_t
{
std::vector<double> points_a;
std::vector<double> points_b;
};
my_result_t function();
{
my_result_t result;
result.points_a.push_back(1.0);
result.points_b.push_back(2.0);
return result;
}
int main()
{
auto result = function();
std::cout << result.points_a[0];
}

Related

Making an array of function pointers [duplicate]

This question already has answers here:
How define an array of function pointers in C
(5 answers)
Closed 4 years ago.
My problem is: I want to write a program which create an array function pointers. I know how to make pointer to function, but don't know how to make array of them.
This is what I tried up to now:
double add(double a, double b) { return a + b; }
double sub(double a, double b) { return a - b; }
double mult(double a, double b) { return a * b; }
double div(double a, double b) { return a/b; }
int main() {
double(*Padd)(double a, double b);
double(*Psub)(double a, double b);
double(*Pmult)(double a, double b);
double(*Pdiv)(double a, double b);
Padd = &add;
Psub = ⊂
Pmult = &mult;
Pdiv = &div;
}
In my code I create these pointers to functions in an array like e.g.
double Tpointers[3];
Tpointers[0] = Padd;
Tpointers[1] = Psub;
Tpointers[2] = Pmult;
Tpointers[3] = Pdiv;
How do I do this?
Simply declare a new type 'Tpointers' that represent a pointer to a function that give two double and return a double.
And in the code you can create an array of functions.
#include<iostream>
// The function pointer type!
typedef double (*Tpointers)(double, double);
double add(double a, double b) { return a + b; }
double sub(double a, double b) { return a - b; }
double mult(double a, double b) { return a * b; }
double div(double a, double b) { return a / b; }
int main() {
// A functions pointers array .
Tpointers fun_array[4];
// Assign the values
fun_array[0] = &add;
fun_array[1] = ⊂
fun_array[2] = &mult;
fun_array[3] = &div;
// A little test
std::cout << fun_array[2](3, 3) << " " << fun_array[3](3,3) << " " << fun_array[1](3,3)
<< std::endl;
return 0;
}
In c++ you can also create an std::vector of functions pointer ... or any containers from the std libraries of "Tpointers".

Set method in a simple c++ class file returning strange values

I am having trouble using a set function in a class file. So far I have the following. I am trying to write a quadratic class that has three private data members and can calculate both the value of a quadratic and the number of real roots in the quadratic. I'm not stuck on the math part as much as I am getting the set methods to not give me weird values. When I test using main, the values for a, b, and c are numbers that I didn't input when I created the object.
Quadratic.hpp
#ifndef QUADRATIC_HPP
#define QUADRATIC_HPP
class Quadratic
{
private:
double a;
double b;
double c;
public:
Quadratic();
Quadratic(double, double, double);
void setA(double);
void setB(double);
void setC(double);
double getA();
double getB();
double getC();
double valueFor(double);
int numRealRoots();
};
#endif
Quadratic.cpp
#include <cmath>
#include <iostream>
Quadratic::Quadratic()
{
setA(1.0);
setB(1.0);
setC(1.0);
}
Quadratic::Quadratic(double A, double B, double C)
{
a = A;
b = B;
c = C;
}
void Quadratic::setA(double A)
{
a = A;
}
void Quadratic::setB(double B)
{
a = B;
}
void Quadratic::setC(double C)
{
c = C;
}
double Quadratic::getA()
{
return a;
}
double Quadratic::getB()
{
return b;
}
double Quadratic::getC()
{
return c;
}
double Quadratic::valueFor(double x)
{
return (a*(pow(x,2)) + b*x + c);
}
int Quadratic:: numRealRoots()
{
double discriminant = pow(b,2) - (4*a*c);
double epsilon = 0.00001;
int realRoots;
if (discriminant <= epsilon && discriminant > 0)
realRoots = 1;
else if (discriminant > epsilon)
realRoots = 2;
else
realRoots = 0;
return realRoots;
}
Your setB method is wrong - it updates a instead of b:
void Quadratic::setB(double B)
{
b = B; // Was "a = B;" in the original code
}

Error when using a function as an argument of a function

I'm trying to create a program to numerically integrate a function between two limits. I've created a minimal example (where the "integral" is always 1.0) to illustrate an error I get. The code below tries to use a function whose arguments are two doubles and a function from doubles to doubles:
#include <iostream>
#include <math.h>
double cons(double a, double b, double c(double d))
{
return 1.0;
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f(x));
std::cout << I << "";
}
This results in an error on cpp.sh:
14:31: error: cannot convert 'double' to 'double ()(double)' for argument '3' to 'double cons(double, double, double ()(double))'
Obviously, the difference between doubles and double-valued functions is causing a problem here. How can I get this working?
You need to pass the function, not call it.
#include <iostream>
#include <math.h>
double cons(double a, double b, double c(double d))
{
return 1.0;
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f);
std::cout << I << "";
}
You didn't pass a function but the result of a function, a double. Second, you didn't correctly declared a function pointer as argument.
If you want to pass a double then declare a double as argument:
double cons(double a, double b, double c)
{
return 1.0*a*b*c;
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f(x));
std::cout << I << "";
}
If you want to pass a function (aka function pointer as C++ is not a functional language):
double cons(double a, double b, double (*c)(double d))
{
return 1.0*c(a);
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f);
std::cout << I << "";
}
Your problem in this case is that you are calling the function with:
double I = cons(0, 1, f(x));
so you actually give cons the return value of f() instead of the actual function. So you need to write this insteed:
double I = cons(0, 1, f);
As an alternativ you could also use lambda expressions for your problem. For example something like this:
#include <iostream>
#include <math.h>
#include <functional>
double cons(double a, double b, const std::function<double(double)>& callback)
{
// do something
}
int main()
{
double x;
double I = cons(0, 1, [](double x){ return x*x});
std::cout << I << "";
}

How to call a function with structure (C++)

My code is not working because I have a problem with the call of my two functions when I use a structure. I think I didn't call it correctly but I'm not sure if the problem is here or in the definition itself.
Here is my code:
#include <stdio.h>
#define NUM 3
struct student{
char name[20];
int kor;
int math;
int eng;
int sum;
double avg;
double avg2;
double k, m, e;
};
void average(student* st)
{
int i, sum = 0;
for(i=0;i<NUM;i++) {
st[i].sum= st[i].kor + st[i].math + st[i].eng;
st[i].avg= st[i].sum / NUM;
}
}
void average2(student* st)
{
int i, sum = 0;
double K, M, E;
for(i=0;i<NUM;i++) {
K+= st[i].kor;
M+= st[i].math;
E+= st[i].eng;
}
}
int main(void)
{
student stu[NUM]={{"Tom"},{"Jane"},{"Eddy"}} ;
int i;
int max;
double K, M, E;
printf("Input scores.\n");
for(i=0;i<NUM;i++)
{ printf("\n<%s>\n",stu[i].name);
printf("Korean:");
scanf("%d",&stu[i].kor);
printf("Math:");
scanf("%d",&stu[i].math);
printf("English:");
scanf("%d",&stu[i].eng);
}
printf("\nName\tKorean\tMath\tEnglish\tSum\tAverage\n");
average(stu);
for(i=0;i<NUM;i++)
printf("%s\t%d\t%d\t%d\t%d\t%.2f\n",stu[i].name,stu[i].kor,stu[i].math,stu[i].eng,stu[i].sum,stu[i].avg);
average2(stu);
printf("Average %.2lf\t%.2lf%.2lf\n", k/3, m/3, e/3);
}
Thank you in advance for your answers, Coco
for loops should have { and } to enclose more than one line in c++.
for(i=0;i<NUM;i++)
{
st[i].sum= st[i].kor + st[i].math + st[i].eng;
st[i].avg= st[i].sum / NUM;
}
Also in your function average2 it is not clear what you are exactly doing.
You are declaring same variable in main and average2 double K, M, E; so the function will take local variable only.
For your second printf here is the logic.,
for(i=0;i<NUM;i++) {
K+= st[i].kor;
M+= st[i].math;
E+= st[i].eng;
}
printf("Average %.2lf\t%.2lf%.2lf\n", K/3, M/3, E/3);

QAWC gsl - could not integrate function

I've got such a piece of code:
#include <gsl/gsl_integration.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
double func1(double x, void* params) {
return 1/(x-1);
}
int main() {
int num = 100;
gsl_integration_workspace *workspace = gsl_integration_workspace_alloc(num);
double result, error;
double alpha;
alpha = 1;
gsl_function F;
F.function = &func1;
F.params = α
double a, b;
a=0;
b=2;
double err1= 0;
double err2 = 1e-7;
gsl_integration_qawc (&F, a, b, 1.0, err1, err2, num, workspace,&result, &error);
printf("Function QAWC - Cauchy Principal value\n");
printf("Result: %f\n", result);
printf("Error: %f\n", error);
result = 0;
gsl_integration_workspace_free(workspace); //zwolnienie pamięci dla całkowania
return 0;
}
I thought that it'll deal with such a kind of function, but I get the "could not integrate function" error. Why?
It's not that hard. Simply the function which will be calculated has a form F(x)=g(x)*w(x), where g(x) is a function which user has to define. w(x) is made using c parameter and has form: w(x)=1/(x-c). So if we want to compute principal value for function f(x)=1/(x-1) func1 should be:
double func1(double x, void* params) {
return 1;
}
And parameter c (4. parameter of function gsl_integration_qawc) sholud be 1.