简体   繁体   中英

Error while running an array within function in python

RuntimeWarning: divide by zero encountered in double_scalars While trying to insert array to an function

import numpy as np
import random

def lagrange(x, y, x_int):
    n = x.size
    y_int = 0

    for i in range(0, n):
        p = y[i]
        for j in range(0, n):
            if i != j:
               p = p * (x_int - x[j]) / (x[i] - x[j])
        y_int = y_int + p
    return [y_int]

x = []
y = []
for i in range(1000):
   x.append(random.randint(0,100))
   y.append(random.randint(0,100))

fx = 3.5
print(lagrange(np.array(x),np.array(y),fx))

i expected to have 1000 iteration of output of an output, any solution to these problems?

Your error message refers to a function not mentioned in your code. But I assume the issue is because x[i] and x[j] could be the same number, and therefore you are dividing by zero on your p = p * (x_int - x[j]) / (x[i] - x[j]) line, which is not possible. You will need to add an exemption to do something different in the case x[i] equals x[j] .

Since you're generating your x array randomly from a range of (0,100) , and the array size is 1000, it's guranteed that x[i] = x[j] for some i,j . You need to ensure elements in x are unique.

See: How do I create a list of random numbers without duplicates?

In your nested loop could it be that you meant to do if x[i] != x[j]:

Those would be the values you wouldn't want to be the same in your division.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM