Friday, September 29, 2023

Calculation of π Using the Monte Carlo Method

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

// Function to generate a random number between 0 and 1
double RandomNumber() {double r=RAND_MAX;
return rand() / r;
}

// Function to estimate π using the Monte Carlo method
double estimatePi(int totalPoints) {
int insideCircle = 0; // Number of points inside the quarter-circle
for (int i = 0; i < totalPoints; ++i) {
double x = RandomNumber(); // Generate random x-coordinate between 0 and 1
double y = RandomNumber(); // Generate random y-coordinate between 0 and 1
// Check if the point (x, y) is inside the quarter-circle (x² + y² <= 1)
if (x * x + y * y <= 1) {
insideCircle++;
}
}
// Estimate π using Monte Carlo method: π/4 ≈ (Number of points inside circle) / (Total number of points)
return 4.0 * static_cast<double>(insideCircle) / totalPoints;
}

int main() {
srand(time(0)); // Seed the random number generator with the current time
int totalPoints = 1000000; // Total number of random points to generate
double estimatedPi = estimatePi(totalPoints);
cout << "Estimated value of π: " << estimatedPi << endl;
return 0;
}



In this program:
We use the random number generator to generate random points in the unit square [0, 1] × [0, 1].
We count the number of points that fall inside the quarter-circle (x^2 + y^2 ≤ 1) by checking if the point satisfies this condition.
Finally, we estimate the value of π using the formula: π/4 ≈ (Number of points inside circle) / (Total number of points).

Compile and run this program, and it will provide an estimated value of π using the Monte Carlo method. The more points you generate (totalPoints), the more accurate the estimate will be. 

The logic for estimating π is encapsulated within the
estimatePi function. The estimatePi function takes the total number of random points as a parameter and returns the estimated value of π. This separation of concerns makes the code more modular and easier to maintain.

C++ program to find the root of a function using Newton's method

In this program:
f(x) is the function for which you want to find the root, and 
df(x) is its derivative. 
You can replace them with your own function and its derivative.
The newton function implements Newton's method to find the root within a specified tolerance and a maximum number of iterations.
In the main function, you can set the initial guess (initial_guess), tolerance (tolerance), and the maximum number of iterations (max_iterations) to control the root-finding process.

Compile and run this program, and it will find an approximate root of the function using Newton's method. 


#include <iostream>
#include <cmath>

using namespace std;

// Define the function for which we want to find the root
double f(double x) {
    return x * x - 4; // Example function: f(x) = x^2 - 4
}

// Define the derivative of the function
double df(double x) {
    return 2 * x; // Derivative of f(x) = x^2 - 4 is f'(x) = 2x
}

// Newton's method to find the root of a function
double newton(double initial_guess, double tol, int max_iterations) {
    double x = initial_guess;
    int iterations = 0;

    while (iterations < max_iterations) {
        double fx = f(x);
        double dfx = df(x);

        if (abs(fx) < tol) {
            return x; // Found a root within tolerance
        }

        x = x - fx / dfx; // Newton's iteration formula
        iterations++;
    }

    cout << "Newton's method did not converge within the specified number of iterations." << endl;
    return NAN; // Not a number (indicating an error)
}

int main() {
    double initial_guess = 2.0; // Initial guess for the root
    double tolerance = 0.0001; // Tolerance for the solution
    int max_iterations = 100; // Maximum number of iterations

    double root = newton(initial_guess, tolerance, max_iterations);

    if (!isnan(root)) {
        cout << "Approximate root: " << root << endl;
    }

    return 0;
}

Bisection Method

The bisection method is a simple numerical method used to find the root of a function. It works by repeatedly bisecting an interval and then narrowing down the interval until the root is found within a desired tolerance. Here's an overview of how the bisection method works:

Start with an initial interval [a, b] such that f(a) and f(b) have opposite signs, which guarantees the existence of a root within the interval.


Compute the midpoint c of the interval: c = (a + b) / 2.


Evaluate the function at the midpoint: f(c).


Determine the new interval:If f(c) is very close to zero (i.e., within the desired tolerance), then c is the root.
If f(c) has the same sign as f(a), the new interval becomes [c, b].
If f(c) has the same sign as f(b), the new interval becomes [a, c].


Repeat steps 2-4 until the root is found or the interval becomes sufficiently small.

The bisection method guarantees convergence to a root because the interval containing the root is halved at each step. However, the rate of convergence is generally slower compared to more advanced methods like Newton's method.

It's worth noting that the bisection method assumes that the function is continuous and that there is only one root within the given interval. Also, it is important to choose a suitable initial interval and tolerance based on the behavior of the function.

Overall, the bisection method is a reliable and robust method for finding the root of a function, particularly when other methods may not be applicable or when simplicity is preferred over speed.


#include <iostream>
#include <cmath>
using namespace std;

// Define the function for which we want to find the root
double f(double x) {
return x * x - 4; // Example function: f(x) = x^2 - 4
}

// Bisection method to find the root of a function
double bisection(double a, double b, double tol) {
if (f(a) * f(b) >= 0) {
cout << "Bisection method cannot be applied. f(a) and f(b) must have opposite signs." << endl;
return NAN; // Not a number (indicating an error)
}
double c;
while ((b - a) >= tol) {
// Find midpoint
c = (a + b) / 2;
// Check if the midpoint is the root
if (f(c) == 0.0) {
return c;
}
// Decide the new interval based on the sign of f(c)
else if (f(c) * f(a) < 0) {
b = c;
} else {
a = c;
}
}
// Return the approximate root within tolerance
return (a + b) / 2;
}

int main() {
double a = 0.0; // Left endpoint of the interval
double b = 5.0; // Right endpoint of the interval
double tolerance = 0.0001; // Tolerance for the solution
double root = bisection(a, b, tolerance);
if (!isnan(root)) {
cout << "Approximate root: " << root << endl;
} else {
cout << "No root found within the given tolerance." << endl;
}
return 0;
}

Friday, September 22, 2023

Flight

 #include <iostream>

using namespace std;

int

main ()

{

  int N = 5, i, j;

  int a[5][5] = 

  { 0, 1, 1, 0, 1,

    0, 0, 0, 1, 0,

    0, 1, 1, 1, 1,

    1, 1, 0, 1, 0,

    0, 0, 1, 1, 1

  };

  cout << "Start? ";

  cin >> i;

  cout << "Finish? ";

  cin >> j;

  if (a[i][j] == 0)

    cout << "No direct flight" << endl;

  else

    cout << "There is a direct flight" << endl;

  int p = 0;

  for (int k = 0; k < N; k++)

    if (a[i][j] == 0)

      if (a[i][k] == 1 && a[k][j] == 1)

{

  cout << "There is a flight from " << i << " to " << j <<

    " with stop in " << k << endl;

  p = 1;

}

  if (p == 0)

    cout << "There is not flight with one stop" << endl;

  return 0;

}


#include <windows.h>

#include <iostream>

#include <math.h>

void drawCircle(int x, int y, int radius) {

// Get the console handle.

HWND consoleHandle = GetConsoleWindow();

// Create a graphics device context for the console.

HDC deviceContext = GetDC(consoleHandle);

// Set the pen color to white.

HPEN pen = CreatePen(PS_SOLID, 1, RGB(255, 255, 255));

SelectObject(deviceContext, pen);

// Calculate the starting and ending points for the circle.

int startX = x - radius;

int startY = y - radius;

int endX = x + radius;

int endY = y + radius;

// Draw the circle.

Ellipse(deviceContext, startX, startY, endX, endY);

// Delete the pen.

DeleteObject(pen);

// Release the graphics device context.

ReleaseDC(consoleHandle, deviceContext);

}

int main() {

// Draw a circle at the center of the console.

drawCircle(400, 400, 100);

// Keep the console window open until the user presses a key.

getchar();

return 0;

}


Friday, September 8, 2023

Calculating the roots of a quadratic equation

 The algorithm for calculating the roots of a quadratic equation is based on the quadratic formula. A quadratic equation is typically expressed in the form:

2++=0

Where:

  • , , and are the coefficients of the equation.
  • represents the variable we're trying to solve for.
  • The equation is set to zero.
  • Example:
  • equation:         2x26x+ 4 0coefficients:     = 2, = -6, = 4.

To find the roots of the quadratic equation, follow these steps:

  1. 1. Input numbers a, b, and c.

  2. 2. Calculate the discriminant (): The discriminant is a value derived from the coefficients , , and and is used to determine the nature of the roots. The discriminant is calculated as:

    =24

  3. Determine the nature of the roots:

    • If >0, there are two distinct real roots.
    • If =0, there is one real root (a repeated root or a double root).
    • If <0, there are no real roots (complex roots).
  4. 3. Calculate the roots based on the value of the discriminant:

    a. If >0: Two distinct real roots.

    • 1=+2
    • 2=2

    b. If =0: One real root.

    • 1=2=2

    c. If <0: No real roots. Complex roots can be expressed as:

    • 1=2+2
    • 2=22 Here, represents the imaginary unit.

These are the fundamental steps for calculating the roots of a quadratic equation. The values of 1 and 2 represent the roots of the equation. Depending on the discriminant, you'll have real or complex roots, and the values of can be calculated accordingly.

N-point Star in Microsoft Visual Studio Console App

#include <windows.h> #include <cmath> #include <iostream> LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,...