Error in Python script

Asked

Viewed 120 times

1

Good afternoon

Can someone explain to me why my code does not give the requested result and what I can do to obtain the requested solution?

Error appears as follows: total = round(sum,Ndec[k])Typeerror: 'list' Object cannot be Interpreted as an integer

Implement a function with three parameters, which, for a given angle in degrees (first parameter), a vector N (second parameter), with increasing values of the number of terms of the series to be used, computes and returns a vector with the value of the approximation of the cosine function obtained with each of the Ni Taylor series terms, for given angle.

The number of decimal places to use in the result for each number of terms is given by the vector NDec (third parameter) with the index i of the vector indicating the number of decimal places to be displayed for the number of terms defined in the index i vector N. The vector N should not be modified by the function.

import math
def taylor(ang,N,NDec):
ang_rad = math.radians(ang)
res = []
soma = 0
for i in range(len(N)): 
    for k in range(len(NDec)):
        for j in range(N[i]):
            aprox_cos = (-1)**j/(math.factorial(2*j)) * ang_rad**(2*j)
            soma = soma + aprox_cos
        total = round(soma,NDec[k])
    res.append(total)
return res

I used it on the console

ang = 180

N=[3, 4, 6, 10, 20]

NDec=[4, 6, 8, 10, 10]

The solution is:

[0.1239, -1.211353, -1.0018291, -1.0000000035, -1.0]

Note: inserir a descrição da imagem aqui

Thanks to those who can help!

2 answers

1

As far as I can tell, there’s one parenthesis left on line 7 and there’s an extra bracket on line 9.

I believe that fixing this errors do not appear. I tested in an online python environment.

  • Thank you for the reply, I have corrected that and edited the question, but it still does not give me the requested result

0

The problem is simple, you are passing the Angule in degrees and the function should receive the angle in radians.

I refactored the code a little bit because I didn’t understand that sum of your initialized out of the loops. I created 2 methods, a called Taylor, which generates the results for each quantity of elements and a compute_cos, which uses the series of Taylor to calculate for 1 element.

def taylor(angle, vector, decimals):
    """Calcula a aproximacao do cosseno usando o metodo de Taylor

    Parameteres
    ----------
    angle : int angulo em graus
    vector : list com a quantidade de iteracoes a serem usadas pra aproximar o resultado
    decimals : quantidade de casas decimais do resultado
    """
    results = []

    for (i, element) in enumerate(vector):        
        _sum = compute_cos(element, angle)

        dec = decimals[i]
        result = round(_sum, dec)        
        results.append(result)

    return results


def compute_cos(iterations, angle):
    """Calcula aproximadamente o coseno de um angulo usando series de Taylor

    Parameters
    ----------
    iterations: quantidade de iteracoes na serie
    angle : int angulo a ser calculado o coseno em graus
    """
    _sum = 0

    angle = math.radians(angle)
    for n in range(iterations):
        fact = math.factorial(2 * n)
        dividendo = (-1) ** n
        cos = (dividendo / fact) * (angle ** (2 * n))
        _sum += cos

    return _sum

Running these results, we get:

angle = 180
elements = [3, 4, 6, 10, 20] 
decimals = [4, 6, 8, 10, 10]
taylor(angle, elements, decimals)
>> [0.1239, -1.211353, -1.0018291, -1.0000000035, -1.0]

That matches the result you expect.

  • Thanks for the reply but could you explain to me why the error appears: total = round(sum,Ndec[k])Typeerror: 'list' Object cannot be Interpreted as an integer , in the code I edited? i in the first loop did i i go through all the elements of N , in the second loop to give the decimal places I want and in the third loop to go through the elements of N[i] (I’m only trying to use a function)

  • Decimals do not need a loop, the round should only be called once for each element of N.

  • understood, but then how does the total end? If you do: total = round(sum,Ndec[i]) .

  • Nothing indicates in your code why of this error. This mistake should happen if Ndec was a list of lists, but it’s not what is written in the code you posted.

  • I already ran the program like this and gives me the result [0.1239, -1.087443, -2.08927202, -3.0892720247, -4.0892720247], that is to say only the first value is correct. how do I fix this?

  • You initialized the sum within the first for?

  • I have put the sum in the first go and already gave me the correct result. It makes sense because what I want to add is the elements of "for j in range(N[i]):" Thank you very much for your help!

Show 2 more comments

Browser other questions tagged

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