Doubt in an equation in Pascal

Asked

Viewed 57 times

0

I’m having a little problem with a code here. The following is requested: Given X as parameter (in degrees), calculate cos(x) with the sum of the first 15 terms of the series below: http://i.imgur.com/sl3DjWV.png

With the compiler I’ve been step by step, but I can’t find the fault. I know I should really find this on my own, but I’ve been in this for a while and getting lost in thought.

The code I made until then:

Program eq;

var
x, i, j, k, switch:integer;
coss:real;

function fatorial(n:integer):real;

var
fatN: real;

begin           
    fatN := 1;  
    for i := 1 to n do
    begin   
        fatN := fatN*i;
    end;
    fatorial := fatN; 
end; 

function expoente(x, y:integer):real;

var
range:integer;

begin
    range := y - 1;
    for k := 1 to range do
    begin
        x := x * x
    end;
    expoente := x;
end;

begin   
    readln(x);
    coss := 0;
    for j := 1 to 15 do
    begin
        if j mod 2 = 1 then
            switch := -1
        else
            switch := 1;
        coss := (coss + ((expoente(x, (j*2)))/(fatorial(j*2)))) * switch;
    end;
    coss := 1 - coss;
    writeln(coss:0:8);
end.

Can anyone imagine where I’m skating?

1 answer

1

This is the Fourier series for cosine.

For exponent use X high to Y:

exp(y*ln(x))

along those lines:

coss := (coss + ((expoente(x, (j*2)))/(fatorial(j*2)))) * switch;

Replace with:

coss := coss + (exp(j*2*ln(x))/(fatorial(j*2)) * switch;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.