Why is this matrix not working in my program?

That's why I decided to use a Vandermonde matrix in my code instead of inverse or Gauss-Jordan elimination. But I managed to solve the problem with that method in the end. In summary, the conversation discusses the use of a matrix and polynomial interpolation to solve a Project Euler problem. The code provided includes a function for calculating a polynomial, a loop to create a matrix, and a while loop to find the correct answer. The conversation also includes a discussion about the range function in Python and ways to debug code.
  • #1
etotheipi
https://projecteuler.net/problem=101
Code:
import numpy as np
for j in range (1,11):
    M = np.empty([j, j])
    for x in range(1,j+1):
        for y in range(1,j+1):
            M[y,x] = y**(j-x)
    Minv = np.linalg.inv(M)
The ##j^{\mathrm{th}}## estimate ##\mathrm{OP}(j,n)## which fits ##j## data points is a ##(j-1)^{\mathrm{th}}## degree polynomial ##u^{(j)}(n) = a_{j-1} n^{j-1} + \dots + a_{0}## which agrees with ##u_n## on the set ##n \in \{1, \dots, j \}##, so$$\mathbf{a} := \begin{pmatrix} a_{j-1} \\ \vdots \\ a_0 \end{pmatrix} = \begin{pmatrix} 1 & 1 & \cdots & 1 \\ 2^{j-1} & 2^{j-2} & \cdots & 1 \\ \vdots & \vdots & & \vdots \\ j^{j-1} & j^{j-2} & \cdots & 1\end{pmatrix}^{-1} \begin{pmatrix} u_1 \\ \vdots \\ u_j \end{pmatrix} := \mathbf{M}^{-1} \mathbf{u}$$I need to make the matrix ##\mathbf{M}##, why does it not work?
Code:
M[y,x] = y**(j-x)
IndexError: index 1 is out of bounds for axis 0 with size 1
 
Last edited by a moderator:
Technology news on Phys.org
  • #2
For the M[x,y] assignment do you mean M[x-1,y-1] ?
 
  • Like
Likes etotheipi
  • #3
oh yeah that's it thanks :smile:
 
Last edited by a moderator:
  • #4
It does not give me the correct answer :frown:
Python:
import numpy as np
sum = 0
def p(k):
    s = 0
    for i in range(0,11):
        s += ((-1)**i)*(k**i)
    return s
for j in range (1,11):
    M = np.empty(shape=(j,j))
    for x in range(1,j+1):
        for y in range(1,j+1):
            M[y-1,x-1] = y**(j-x)
    Minv = np.linalg.inv(M)
    U = np.empty(shape=(j,1))
    for i in range(1, j+1):
        U[i-1] = p(i)
    A = np.matmul(Minv, U)
    z = 1
    FIT_found = False
    while(FIT_found == False):
        estimate = 0
        for r in range(0,j):
            estimate += A[r]*z**r
        if(estimate != p(z)):
            sum += estimate
            FIT_found = True
        else:
            z = z + 1      
print(sum)
 
Last edited by a moderator:
  • #5
etotheipi said:
It does not give me the correct answer :frown:
I think the idea of doing Project Euler problems is to work on your code until it does :smile:

When posting code here it helps if you add the language so syntax highlighting works:
Python:
import numpy as np
sum = 0
def p(k):
    s = 0
    for i in range(0,11):
        s += ((-1)**i)*(k**i)
    return s
for j in range (1,11):
    M = np.empty(shape=(j,j))
    for x in range(1,j+1):
        for y in range(1,j+1):
            M[y-1,x-1] = y**(j-x)
    Minv = np.linalg.inv(M)
    U = np.empty(shape=(j,1))
    for i in range(1, j+1):
        U[i-1] = p(i)
    A = np.matmul(Minv, U)
    z = 1
    FIT_found = False
    while(FIT_found == False):
        estimate = 0
        for r in range(0,j):
            estimate += A[r]*z**r
        if(estimate != p(z)):
            sum += estimate
            FIT_found = True
        else:
            z = z + 1
print(sum)
 
  • Like
Likes etotheipi
  • #6
I always get confused by Python's range() function: note that range(1, 11) gives you [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: this is the first thing I'd check.

And then i'd check that my j, x, and y values are doing what I want in the inner loop (either with an IDE or a simple print statement).

Edit: first of all I'd refactor it so all my loops start at 0, it makes it much easier to keep track.
 
  • Like
Likes etotheipi
  • #7
thanks okay I'm going to finish this tomorrow because I have homework and my stupid code is giving me -670.99996864
 
  • Haha
Likes pbuk
  • #8
etotheipi said:
thanks okay I'm going to finish this tomorrow because I have homework and my stupid code is giving me -670.99996864
:eek: yeah, I don't think that's right.
 
  • #9
pbuk said:
I always get confused by Python's range() function: note that range(1, 11) gives you [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: this is the first thing I'd check.

And then i'd check that my j, x, and y values are doing what I want in the inner loop (either with an IDE or a simple print statement).

Edit: first of all I'd refactor it so all my loops start at 0, it makes it much easier to keep track.

That’s how I checked the code. I called that seldom used secret programmers function:

Python:
print(‘j = %d, x = %d, y = %d’%(j,x,y))

just before his M assignment.
 
  • #10
I'd look for a simpler method of polynomial interpolation if I were you.
 

Related to Why is this matrix not working in my program?

1. Why am I getting an error when I try to run my program with this matrix?

There could be a few reasons why you are getting an error with your matrix. Some common reasons include:
- The dimensions of the matrix do not match the dimensions specified in your code.
- The matrix contains non-numeric values, such as strings or characters.
- You are trying to perform an operation on the matrix that is not supported, such as taking the square root of a negative value.
To fix this error, double check the dimensions and values of your matrix, and make sure the operations you are performing are valid for matrices.

2. Why is my program outputting incorrect results when I use this matrix?

If your program is outputting incorrect results with a matrix, there are a few possible reasons:
- The matrix contains errors, such as missing or incorrect values.
- Your code is using the wrong matrix or the wrong sections of the matrix.
- Your matrix operations are not correctly implemented.
To fix this issue, check that your matrix is error-free and that your code is correctly accessing and manipulating the matrix.

3. Can I use this matrix with any type of data?

Matrices are most commonly used with numeric data, but they can also be used with other types of data, such as strings or characters. However, keep in mind that certain operations may not be valid for non-numeric matrices. For example, you cannot perform mathematical operations on a matrix of strings.

4. How can I optimize my code to work with larger matrices?

If your code is working with smaller matrices but encountering performance issues with larger matrices, there are a few ways to optimize it:
- Use built-in matrix functions or optimized libraries instead of writing your own code.
- Reduce the number of nested loops in your code.
- Use data structures, such as sparse matrices, to reduce the amount of memory needed for larger matrices.
- Consider parallelization or vectorization techniques to speed up operations on large matrices.

5. Is there a way to debug my code when working with matrices?

Yes, there are several ways to debug your code when working with matrices:
- Use print statements to check the values of your matrices and variables at different points in your code.
- Use a debugger tool to step through your code and see how it is executing.
- Use visualization tools to see how your matrices are changing and how the values are being manipulated.
- Use unit tests to check the outputs of your code against expected results.
- Ask for help from a colleague or seek assistance from online communities.

Similar threads

  • Programming and Computer Science
Replies
31
Views
2K
Replies
1
Views
1K
  • Calculus and Beyond Homework Help
Replies
4
Views
1K
  • Advanced Physics Homework Help
Replies
8
Views
853
Replies
5
Views
482
  • Calculus and Beyond Homework Help
Replies
4
Views
1K
  • Programming and Computer Science
3
Replies
75
Views
4K
  • Math Proof Training and Practice
Replies
8
Views
1K
  • Topology and Analysis
Replies
12
Views
3K
Back
Top