This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Here's my attempt to encode the bisection method in C (give me a bit of a break veteran C people, I am but a mere high-level language user and might have designed it poorly). The crucial feature is that it takes a function as an argument, some of the details of which perhaps I don't understand perfectly (still figuring out pointers - although I'm told we're all still figuring out pointers):
#include <iostream>
#include <cmath>
double bisectionMethod(double (*f)(double), double a, double b, double eps)
{
if (b <= a) {
double switchVal = a;
a = b;
b = switchVal;
}
if ((*f)(a)*((*f)(b)) > 0) {
return -999.0;
}
while ((b-a) > eps) {
double middle = ((b a)/2.0);
if (((*f)(middle)) * ((*f)(b)) > 0) {
b = middle;
}
else if (((*f)(middle)) * ((*f)(a)) > 0) {
a = middle;
}
else if (((*f)(middle)) == 0.0) {
return middle;
}
}
return ((b a)/2.0);
}
This function works on its own in a C file, and as an example, you may use the above function with the following example so that you can reproduce its functioning (the answer it outputs should be a decent approximation of ln(2)):
double fexample(double x)
{
double y = (std::exp(x)-2);
return y;
}
int main()
{
std::cout << bisectionMethod(fexample, 0, 3, 0.0000001) << std::endl;
return 0;
}
Now, I'm using the Rcpp package to try and make this function callable in R (if I don't get any answer here I will do the circuit of R help subreddits/email lists). However that has so far failed, and the reason Rcpp gave was that f was an undeclared identifier, which is not a problem it had when I ran the function separately.
That requires:
// [[Rcpp::export]]
Directly above the function and:
#include <Rcpp.h>
using namespace Rcpp;
Added to the include statements at the top.
So my question is, what am I doing wrong? What do I change? And I guess, how do you make functional programming in C and R speak with each other since that seems to be the root of the problem.
EDIT: Previously when people have asked similar questions, people seem to get caught up on the fact that the post is implementing a very simple function with better implementations in both languages. You're right, there's probably a bisection method in some C package and another already implemented using Rcpp in some R package somewhere. But I am learning, not trying to provide a service to the R/C community, so my purpose was not to try to 'fix something that isn't broken'.
Since implementing the bisection method is a super common homework question for people learning C in classes, I might censor the function after there's a useful answer to my query if others think that's a good idea.
Subreddit
Post Details
- Posted
- 6 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/cpp_questio...