modifying regula falsi method to the secant method - c

I have implemented the regula falsi method. I am trying to modify it so it becomes the secant method. A pdf I read mentioned that it is essentially the same with just one change.
Future guesses for my 'm' value should have a slightly different formula, instead of:
m = a - f(a) * ( (b-a)/( f(b)-f(a) ) );
it should be:
m = a - f(a) * ( (m-a)/( f(m)-f(a) ) );
but unfortunately it doesn't work (It never finds the root). What should I fix to get this into the secant method?
source code as follows:
#include <stdio.h>
#include <math.h>
void
secant(double a, double b, double e, double (*f)(double), int maxiter ) {
double m, fm, fa, fb;
int i;
fa=(*f)(a);
fb=(*f)(b);
m = a - fa * ( (b-a)/( fb - fa ) );
fm=(*f)(m);
for(i=0; i<maxiter; i++) {
if ( fabs(fm) <= e ) {
printf("f(%f) = %f\n", m, fm);
return;
} else if ((fa*fm) < 0) {
b=m;
fb=fm;
} else {
a=m;
fa=fm;
}
// the guess below works for regula falsi method:
// m = a - fa * ( (b-a)/(fb - fa));
//this was supposed to be the change to turn this into the secant method
m = a - fa * ( (m-a)/(fm - fa) );
fm=(*f)(m);
}
}
int main(){
secant(1,4,0.0001,sin,500);
return 0;
}
Thanks in advance
EDIT: Ok after playing around with pen and paper I finally got it it wasnt a simple change as I initially thought:
void secant(double a, double b, double e, double (*f)(double), int maxiter ) {
double m, fm, fa, fb;
int i;
fa=(*f)(a);
fb=(*f)(b);
for(i=0; i<maxiter; i++) {
m = a - fa * ( (b-a)/(fb - fa) );
fm=(*f)(m);
if ( fabs(fm) <= e ) {
printf("f(%f)=%f, iter: %d\n", m,fm,i);
return;
}
a=b;
b=m;
fa=fb;
fb=fm;
}
}

It's easier for the secant method to not find the root. Are you sure it should find it?
For testing, here is an example: http://www.mathcs.emory.edu/ccs/ccs315/ccs315/node18.html
(example 4.7) You'd want to run that example ( f(x)=x^6-x-1 , x0=1 x1=2, root x=1.347)

Either the PDF is wrong or you misunderstood it. Without reading the PDF it is impossible to say which or explain further. When I explain both methods, I say that the difference between regula falsi and secant method is the rule for updating a and b.
Compute the first two iterations of the secant method by hand. Then modify your program to print the values of a, b and m at every iteration (or use a debugger). That should give you a hint of what is happening.
On your example, the secant method should converge in a few iterations.

Secant method is an open-bracket method, whereas Regula-Falsi is closed-bracket type. So, your PDF is correct. To modify Regula-Falsi method to secant method you have to change the closed-bracket to open type.
See this example for Regula-Falsi method.
Here, the coding is such that one interval always remains constant.
Now, here is a sample program for Secant method.
Here, like the Regula method, two initial guesses are taken, but both the intervals keep on changing until the correct root is obtained. Obtain the initial two guesses manually.
And, about the rate of convergence, for Secant method it is super-linear, whereas for Regula it is linear. So, secant method converges way faster.

Related

pass struct of arrays into function

I am trying to pass a struct of 2D arrays and to do calculations on them.
typedef struct{
float X[80][2];
float Y[80][2];
float Z[80][2];
int T[80][2];
int K[80];
} STATS;
void MovingAverage(STATS *stat_array, int last_stat) {
//Average = Average(Prev) + (ValueToAverage/n) - (Average(Prev)/n)
stat_array->**X**[last_stat][0] = stat_array->**X**[last_stat][0] +
(stat_array->**X**[last_stat][1] / stat_array->T[last_stat][0]) -
(stat_array->**X**[last_stat][0] / stat_array->T[last_stat][0]);
}
calling the function:
MovingAverage(*stat_array, last_stat);
My question is:
how do I access in a generic way to X Y and Z inside MovingAverage function?
Edit:
void MovingAverage(STATS *stat_array, int last_stat, (char *(array_idx)) {
//Average = Average(Prev) + (ValueToAverage/n) - (Average(Prev)/n)
stat_array->**array_idx**[last_stat][0] =
stat_array->**array_idx**[last_stat][0] +
(stat_array->**array_idx**[last_stat][1] /
stat_array->T[last_stat][0]) -
(stat_array->**array_idx**[last_stat][0] /
stat_array->T[last_stat][0]);
}
I know it won't work, but just to demonstrate my willings,
Somebody here (not me) could probably come up with some preprocessor magic to do what you're asking, but that is a solution I would not pursue. I consider it bad practice since macros can quickly get hairy and tough to debug. You can't have "variables" inside your source code, if that makes sense. During the build procedure, one of the first things that runs is the preprocessor, which resolves all your macros. It then passes that source code to the compiler. The compiler is not going to do any text substitutions for you, it cranks on the source code it has. To achieve what you want, write a function that operates on the type you want, and call that function with all your types. I'd change your MovingAverage function to something like this:
void MovingAverage(float arr[80][2], const int T[80][2], int last_stat)
{
arr[last_stat][0] = ... // whatever calculation you want to do here
}
int main(void)
{
STATS stat_array;
int last_stat;
// .. initialize stat_array and last_stat
// now call MovingAverage with each of your 3 arrays
MovingAverage(stat_array.X, stat_array.T, last_stat);
MovingAverage(stat_array.Y, stat_array.T, last_stat);
MovingAverage(stat_array.Z, stat_array.T, last_stat);
...
return 0;
}

making 3d array with arma::cube in Rcpp shows cube error

I am making a Rcpp code for Gibbs sampling. Inside the code, I first want to make a 3 dimensional array with row number= number of iteration (500), column number=number of parameter(4) and slice number= number of chain(3). I wrote it in this way:
#include <RcppArmadillo.h>
#include <math.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace std;
using namespace arma;
//Gibbs sampling code starts here
Rcpp::List mcmc(const int iter,const int chains, const NumericVector data){
arma::cube posteriorC = arma::zeros(iter, 5, chains);
\\ rest of the codes
List out(Rcpp::List::create(Rcpp::Named("posteriorC") =posteriorC));
return out;
}
. While compelling it does not show any error. But when I want to run the code with:
res<- mcmc(iter=500,chains=2,data)
it shows the error:
Error: Cube::operator(): index out of bounds
. I want to know if there any mistake while making the 3D array. Please note that I want to get estimates of 5 parameters of my model.
You need to specify the template for arma::zeros to correctly fill an arma::cube, c.f. arma::zeros<template>
Generate a vector, matrix or cube with the elements set to zero
Usage:
vector_type v = zeros<vector_type>( n_elem )
matrix_type X = zeros<matrix_type>( n_rows, n_cols )
matrix_type Y = zeros<matrix_type>( size(X) )
cube_type Q = zeros<cube_type>( n_rows, n_cols, n_slices )
cube_type R = zeros<cube_type>( size(Q) )
Thus, in your case it would be:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
Rcpp::List mcmc(const int iter, const int chains,
const Rcpp::NumericVector data){
arma::cube posteriorC = arma::zeros<arma::cube>(iter, 5, chains);
// --------------------------------- ^^^^^^^^
// Not Shown
Rcpp::List out = Rcpp::List::create(Rcpp::Named("posteriorC") =posteriorC);
return out;
}
Two final notes:
You explicitly state that the code as it stands now will create 4 columns to store 4 variables. However, you explicitly mention that you needed to estimate 5 parameters. You may need to increase this to prevent an out of bounds when saving into the arma::cube slices.
The way the Rcpp::List out is being created isn't quite correct. In general, the best way to create the list is to do: Rcpp::List out = Rcpp::List::create(Rcpp::Named("Blah"), Blah);

Function definition not allowed / [closed]

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 8 years ago.
Improve this question
My professor gave us this code in class to show how a program works and said "go home and try it and you'll see it works".... well after 30 minutes I cannot get it to run. can someone please help me and point me in the right direction. Thank you!
-I get function definition on the end "double g(double x)"
-On the first else where x_left = x_mid control reaches end of non-void function
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define FALSE 0
#define TRUE 1
#define NO_ROOT -99999.0
//function prototypes
double bisect(double, double, double, double f(double farg));
// evaluation of function
double g(double);
double h(double);
int main(void) {
double x_left, x_right, epsilon, root; //declare variables
// get endpoint and error tolerance
printf("\nEnter interval endpoints > ");
scanf("%lf%lf", &x_left, &x_right);
printf("\nEnter tolerance > ");
scanf("%lf", &epsilon);
//use bisect function to look for roots of functions
printf("\n\n For function g(x)");
root = bisect(x_left, x_right, epsilon, g);
if (root != NO_ROOT)
printf("\n g(%.7f) = %e\n", root, g(root));
printf("\n\n For function h(x)");
root = bisect(x_left, x_right, epsilon, h);
if (root != NO_ROOT)
printf("\n h(%.7f) = %e\n", root, h(root));
system("pause");
return (0);
}
// bisection method program coding
double bisect(double x_left, double x_right, double epsilon, double f(double farg)){
double x_mid, f_left, f_right, f_mid;
int root_found;
// computes function at initial end points
f_left = f(x_left);
f_right = f(x_right);
// if no change in sign
if (f_left * f_right > 0) {
printf("\nmay not be no root in [%.7f, %.7f]\n\n", x_left, x_right);
return NO_ROOT;
}
// searches as long as interval size is large enough
root_found = FALSE;
while (fabs(x_right - x_left) > epsilon && !root_found) {
// compute the mid point
x_mid = (x_left + x_right) / 2.0;
f_mid = f(x_mid);
if (f_mid == 0.0) {
root_found = TRUE;}
else if (f_left * f_mid < 0.0) {
x_right = x_mid;
} else {
x_left = x_mid;
}
// trace loop execution
if (root_found)
printf("\nRoot found at x = %.7f , midpoint of [%.7f, %.7f] ", x_mid, x_leftx_right);
else
printf("\nNew interval is [%.7f, %.7f] \n\n", x_left, x_right);
//if there is a root
return ((x_left + x_right)/2.0);
}
// functions for which roots are sought
double g(double x){
return (5 * pow(x, 3.0) - 2 * pow(x, 2.0) +3);
}
double h(double x){
return (pow(x, 4.0) - 3 * pow(x,2.0) - 8);
};
}
I get an error on this line:
printf("\nRoot found at x = %.7f , midpoint of [%.7f, %.7f] ", x_mid, x_leftx_right
saying that x_leftx_right is undeclared.
If I change this to x_left, x_right then it compiles OK except for "undefined reference to g" and "undefined reference to h".
The reason for the undefined reference to g is that you never provided a function definition for the function g that was prototyped by double g(double);. You did provide a nested function g within bisect. Nested functions are a non-standard extension, and bisect::g is a different function to g. Similarly for h.
To fix this, move the definitions of g and h to be after the end of the bisect function; instead of inside that function.
The reason for your "control reaches end of non-void function" warning is probably because there is no return statement after the while loop.
Your line return ((x_left + x_right)/2.0); line is within the loop begun by while (fabs(x_right - x_left) > epsilon && !root_found) {. If this loop finishes by the loop condition no longer being true, then the execution hits the end of the function without returning anything.
NB. If you indent your code properly so that you line up { then you are less likely to have this sort of problem. Your editor should have a key that you can use to find matching curly-braces. Also, operating your compiler in strict standard mode would have given an error about the use of nested function.
`

How to make external Mathematica functions interruptible?

I had an earlier question about integrating Mathematica with functions written in C++.
This is a follow-up question:
If the computation takes too long I'd like to be able to abort it using Evaluation > Abort Evaluation. Which of the technologies suggested in the answers make it possible to have an interruptible C-based extension function? How can "interruptibility" be implemented on the C side?
I need to make my function interruptible in a way which will corrupt neither it, nor the Mathematica kernel (i.e. it should be possible to call the function again from Mathematica after it has been interrupted)
For MathLink - based functions, you will have to do two things (On Windows): use MLAbort to check for aborts, and call MLCallYieldFunction, to yield the processor temporarily. Both are described in the MathLink tutorial by Todd Gayley from way back, available here.
Using the bits from my previous answer, here is an example code to compute the prime numbers (in an inefficient manner, but this is what we need here for an illustration):
code =
"
#include <stdlib.h>
extern void primes(int n);
static void yield(){
MLCallYieldFunction(
MLYieldFunction(stdlink),
stdlink,
(MLYieldParameters)0 );
}
static void abort(){
MLPutFunction(stdlink,\" Abort \",0);
}
void primes(int n){
int i = 0, j=0,prime = 1, *d = (int *)malloc(n*sizeof(int)),ctr = 0;
if(!d) {
abort();
return;
}
for(i=2;!MLAbort && i<=n;i++){
j=2;
prime = 1;
while (!MLAbort && j*j <=i){
if(i % j == 0){
prime = 0;
break;
}
j++;
}
if(prime) d[ctr++] = i;
yield();
}
if(MLAbort){
abort();
goto R1;
}
MLPutFunction(stdlink,\"List\",ctr);
for(i=0; !MLAbort && i < ctr; i++ ){
MLPutInteger(stdlink,d[i]);
yield();
}
if(MLAbort) abort();
R1: free(d);
}
";
and the template:
template =
"
void primes P((int ));
:Begin:
:Function: primes
:Pattern: primes[n_Integer]
:Arguments: { n }
:ArgumentTypes: { Integer }
:ReturnType: Manual
:End:
";
Here is the code to create the program (taken from the previous answer, slightly modified):
Needs["CCompilerDriver`"];
fullCCode = makeMLinkCodeF[code];
projectDir = "C:\\Temp\\MLProject1";
If[! FileExistsQ[projectDir], CreateDirectory[projectDir]]
pname = "primes";
files = MapThread[
Export[FileNameJoin[{projectDir, pname <> #2}], #1,
"String"] &, {{fullCCode, template}, {".c", ".tm"}}];
Now, here we create it:
In[461]:= exe=CreateExecutable[files,pname];
Install[exe]
Out[462]= LinkObject["C:\Users\Archie\AppData\Roaming\Mathematica\SystemFiles\LibraryResources\
Windows-x86-64\primes.exe",161,10]
and use it:
In[464]:= primes[20]
Out[464]= {2,3,5,7,11,13,17,19}
In[465]:= primes[10000000]
Out[465]= $Aborted
In the latter case, I used Alt+"." to abort the computation. Note that this won't work correctly if you do not include a call to yield.
The general ideology is that you have to check for MLAbort and call MLCallYieldFunction for every expensive computation, such as large loops etc. Perhaps, doing that for inner loops like I did above is an overkill though. One thing you could try doing is to factor the boilerplate code away by using the C preprocessor (macros).
Without ever having tried it, it looks like the Expression Packet functionality might work in this way - if your C code goes back and asks mathematica for some more work to do periodically, then hopefully aborting execution on the mathematica side will tell the C code that there is no more work to do.
If you are using LibraryLink to link external C code to the Mathematica kernel, you can use the Library callback function AbortQ to check if an abort is in progress.

Taking a second derivative in FFTW3

I have tested my code for some real functions using a forward FFT and IFFT (normalized the result), this works fine.
I would, however, like to take a second derivative of a real function. For simplicity sake, I take sin(2*pi*t) as a test case. Here is the relevant code I use (FFT functions in a library):
int main(void)
{
int i;
int nyh = (N/2) + 1;
double result_array[nyh][2];
double x_k[nyh][2];
double x_r[N];
FILE* psit;
psit=fopen("psitest.txt","w");
init();
fft(x, result_array); //function in a library, this has been tested
psi(result_array, x_k);
ifft(x_k, x_r); //function in a library, this has been tested
for(i=0;i<N;i++)
{
fprintf(psit, "%f\n", x_r[i]);
}
fclose(psit);
return 0;
}
void psi(double array[nyh][2], double out[nyh][2])
{
int i;
for ( i = 0; i < N/2; i++ )
{
out[i][0] = -4.0*pi*pi*i*i*array[i][0];
out[i][1] = -4.0*pi*pi*i*i*array[i][1];
}
out[N/2][0]=0.0;
out[N/2][1]=0.0;
}
void init()
{
int i;
for(i=0;i<N;i++)
{
x[i] = sin(2.0*pi*i/N);
}
}
Now here is the problem: This algorithm works perfectly for any function of the form sin( 2*pi*t*K), where K is an integer, but if I take as a test function sin(3*pi*t), the algorithm fails. I am not able to see the mistake in my coding.
Please note that because the function is real, I only need to take half of the k values. This is not the problem.
My guess is that sin(3*pi*t) introduces a discontinuity, since it does not give an integer number of cycles in your sample interval. For most FFT-related applications you would apply a window function to deal with such discontinuities, but obviously this will introduce an error term into your derivative and I'm not sure whether you will be able to correct for this.
I don't know if you have fixed this problem... But I guess the major problem is that sin(3 Pi t) is not periodic in the domain [0,1](sin(0) != sin (3 * Pi)).
FFT could not work properly...

Resources