Skip to main content

Posts

Showing posts from March, 2019

C Program for Bisection Method

#include<stdio.h> #include<math.h> float fun (float x) {     return (x*x*x - 4*x - 9); } void bisection (float *x, float a, float b, int *itr) /* this function performs and prints the result of one iteration */ {     *x=(a+b)/2;     ++(*itr);     printf("Iteration no. %3d X = %7.5f\n", *itr, *x); } void main () {     int itr = 0, maxmitr;     float x, a, b, allerr, x1;     printf("\nEnter the values of a, b, allowed error and maximum iterations:\n");     scanf("%f %f %f %d", &a, &b, &allerr, &maxmitr);     bisection (&x, a, b, &itr);     do     {         if (fun(a)*fun(x) < 0)             b=x;         else             a=x;         bisection (&x1, a, b, &itr);         if (fabs(x1-x) < allerr)         {             printf("After %d iterations, root = %6.4f\n", itr, x1);            

Builds a graph with errors, displays it and saves it as image

// Builds a graph with errors, displays it and saves it // as image. First, include some header files (within, // CINT these will be ignored). #include "TCanvas.h" #include "TROOT.h" #include "TGraphErrors.h" #include "TF1.h" #include "TLegend.h" #include "TArrow.h" #include "TLatex.h" void macro1() { // The values and the errors on the Y axis const int n_points=10; double x_vals[n_points]={1,2,3,4,5,6,7,8,9,10}; double y_vals[n_points]={6,12,14,20,22,24,35,45,44,53}; double y_errs[n_points]={5,5,4.7,4.5,4.2,5.1,2.9,4.1,4.8,5.43}; // Instance of the graph TGraphErrors graph(n_points,x_vals,y_vals,NULL,y_errs); graph.SetTitle("Measurement XYZ;lenght [cm];Arb.Units"); // Make the plot looks better graph.SetMarkerStyle(kOpenCircle); graph.SetMarkerColor(kBlue); graph.SetLineColor(kBlue); // The canvas on which we'll draw the graph TCanvas* mycanvas = new TCanvas(); // Draw the graph ! graph.DrawClone(&quo

Drawing the interference pattern of light falling on a grid

// Example drawing the interference pattern of light // falling on a grid with n slits and ratio r of slit // width over distance between slits. // function code in C double single(double *x, double *par) { double const pi=4*atan(1.); return pow(sin(pi*par[0]*x[0])/(pi*par[0]*x[0]),2); } double nslit0(double *x,double *par) { double const pi=4*atan(1.); return pow(sin(pi*par[1]*x[0])/sin(pi*x[0]),2); } double nslit(double *x, double *par) { return single(x,par) * nslit0(x,par); } // This is the main program void slits() { float r,ns; // request user input cout << "slit width / g ? "; scanf("%f",&r); cout << "# of slits ? "; scanf("%f",&ns); cout <<"interference pattern for "<< ns <<" slits, width/distance: "<<r<<endl; // define function and set options TF1 *Fnslit = new TF1("Fnslit",nslit,-5.001,5.,2); Fnslit->SetNpx(500); /