fprintf('Group 2\n');
  fprintf('Math 130\n');
  fprintf('Numerical Solutions to CE Problems\n');
  fprintf('Laboratory No. 1\n');
function root = secant_method(f, a, b, tol, max_iter)

    fprintf('Iter   a          b          x          Error\n');

    for iter = 1:max_iter
        x = b - (f(b) * (b - a)) / (f(b) - f(a));
        error = abs(x - b);

        fprintf('%3d   %8.6f   %8.6f   %8.6f   %8.6f\n', iter, a, b, x, error);

        if error < tol
            root = x;
            return;
        end

        a = b;
        b = x;
    end

    error('Secant method did not converge to the desired tolerance within maximum iterations.');
end

% Define the function to find the root of (x^2 - 5)
f = @(x) x^2 – 5;

% Initial guesses and tolerance
a = 2.0;
b = 3.0;
tolerance = 1e-6;

% Maximum number of iterations
max_iterations = 10;

% Call the secant_method function to find the root
root = secant_method(f, a, b, tolerance, max_iterations);

fprintf('Root found: %8.6f\n', root);

 

Octave online compiler

Write, Run & Share Octave code online using OneCompiler’s Octave online compiler for free. It’s a simple and powerful platform to practice numerical computations and matrix operations using GNU Octave right from your browser.

About Octave

GNU Octave is an open-source high-level programming language primarily intended for numerical computations. It is mostly compatible with MATLAB, and it's commonly used for linear algebra, numerical analysis, signal processing, and other scientific computing tasks.

Sample Code

The following is a simple Octave program that prints a greeting:

printf("Hello, OneCompiler!\n");

Taking inputs (stdin)

OneCompiler’s Octave editor supports stdin through the I/O tab. Here's an example of reading input from the user:

name = input("Enter your name: ", "s");
printf("Hello, %s!\n", name);

Syntax Basics

Variables

a = 10;
b = 3.14;
name = "Octave";

Vectors and Matrices

v = [1, 2, 3];
M = [1, 2; 3, 4];

Arithmetic

OperationSyntax
Add+
Subtract-
Multiply*
Divide/
Element-wise.*, ./

Conditionals

x = 10;
if x > 5
    disp("x is greater than 5");
else
    disp("x is 5 or less");
end

Loops

For loop

for i = 1:5
    disp(i);
end

While loop

i = 1;
while i <= 5
    disp(i);
    i = i + 1;
end

Functions

function y = square(x)
    y = x ^ 2;
end

result = square(4);
printf("Square: %d\n", result);

This guide provides a quick reference to Octave programming syntax and features. Start writing Octave code using OneCompiler’s Octave online compiler today!