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?

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.