0

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?

Hensel
  • 17
  • 5
  • to handle zero division error, use `np.divide()`: https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.divide.html – Masoud Jul 06 '19 at 20:48

3 Answers3

2

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].

M Somerville
  • 4,499
  • 30
  • 38
2

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?

hoodakaushal
  • 1,253
  • 2
  • 16
  • 31
0

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.

Brad
  • 1
  • 1