Home > Software engineering >  How to perform quuadrature summation in python 3 if a list containing floats is given?
How to perform quuadrature summation in python 3 if a list containing floats is given?

Time:02-10

import math

data = [1.2, 1.4, 0.1, 0.3, 0.5, 0.7, 0.01, 0.8, 0.6, 0.2]


def SumInQuadrature(*args):
    for i in data:
        x = math.sqrt(math.pow(data[i], 2)   math.pow(data[i] 1, 2))
    print(x)

SumInQuadrature()

The above code is what I have so far but it keeps giving an error.

CodePudding user response:

There are several issues:

  • Your function accepts an argument (*args) that it doesn't use and uses a global variable instead (data). It should receive the list as argument.

  • for i in data will give you values in i, not indexes so your calculation should use i directly, not data[i] (with Python you can and should avoid using indexes whenever possible)

  • you're placing the result in the x variable that you override at every iteration. This will give you the last result at best but not an operation on all elements.

  • If you're expecting data[i] 1 to give you the next value, it won't. If i was an index, you could do data[i 1], but as mentioned above, it is not. Besides, only processing the next item will not give you a result that takes the whole list into account. There is also an issue with i 1 going out of bounds when you reach the last item.

  • your function prints a result. It should return it to the caller. Printing should always be separate from calculations.,

  • you are calling your function without supplying the data as parameter. since it uses the global variable, this may still work but that's not how functions are supposed to be used

If you are looking to get the square root of the sum of squares, here's how your function could be implemented:

def SumInQuadrature(valueList):
    result = 0
    for value in valueList:
        result  = value * value    # add up each squared value
    return value ** 0.5            # return the square root of the sum

usage:

data = [1.2, 1.4, 0.1, 0.3, 0.5, 0.7, 0.01, 0.8, 0.6, 0.2]

print(SumInQuadrature(data))

# 0.4472135954999579

If the square root of the sum of square (aka root sum squared or Euclidian norm) is not what you are attempting to get, please indicate it clearly in your question and provide an expected result that we can check answers against. (doing the computation manually may help you understand how your program should proceed)

  •  Tags:  
  • Related