find the (approximate) value of y(0.5) for dy/dt = t^2 + y^2, y(0)=1 on the interval [0, 0.5] in javascript in matlab

In JavaScript, you can approximate the value of y(0.5) for the given initial value problem dy/dt = t^2 + y^2, y(0) = 1 on the interval [0, 0.5] using numerical methods such as Euler's method. Here is an example implementation in JavaScript:

index.tsx
function f(t, y) {
    return Math.pow(t, 2) + Math.pow(y, 2);
}

function eulerMethod(h, n) {
    let t = 0;
    let y = 1;

    for (let i = 1; i <= n; i++) {
        y = y + h * f(t, y);
        t = i * h;
    }

    return y;
}

const h = 0.1; // Step size
const n = 5; // Number of steps to take 

const result = eulerMethod(h, n);
console.log(result);
358 chars
22 lines

In Matlab, you can do the same using the following code:

main.m
function dy = f(t, y)
    dy = t^2 + y^2;
end

h = 0.1; % Step size
n = 5; % Number of steps to take

t = 0;
y = 1;

for i = 1:n
    y = y + h * f(t, y);
    t = i * h;
end

disp(y);
183 chars
17 lines

These scripts will numerically approximate the value of y(0.5) using Euler's method on the specified interval. Remember to adjust the step size h and the number of steps n for better accuracy.

related categories

gistlibby LogSnag