Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Long For Loop Excecution Time

I am attempting to compare the numerical output of a MATLAB script to that of numpy.

The task, from a homework assignment, is to add the value of 10^-N to itself 10^N times.

The goal is to demonstrate that computers have limitations that will compound in such a calculation. The result should always be 1, but as N increases, the error will also increase. For this problem, N should be 0, 1, 2, …, 8.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My MATLAB script runs quickly with no issues:

solns = zeros(1, 9);

for N = 0:8
    for ii = 1:(10^N)
        solns(N+1) = solns(N+1) + 10^-N;
    end
end

However, using Python 3.8.12 on an Anaconda installation with numpy, this code will not terminate:

import numpy as np

solns = np.zeros((9, 1))

for N in range(len(solns)):
    for _ in range(10**N):
        solns[N] += (10**-N)

Is there an error in the Python code or is there some significance difference between the languages that creates this result.

EDIT:

I let the python code run for awhile and it eventually terminated after 230 seconds. The whole array printed out as just [1., 1., 1., etc.].

>Solution :

You’re rather abusing NumPy there. Especially the += with an array element seems to take almost all of the time.

This is how I’d do it, takes about 0.5 seconds:

from itertools import repeat

for N in range(9):
    print(sum(repeat(10**-N, 10**N)))

Output:

1
0.9999999999999999
1.0000000000000007
1.0000000000000007
0.9999999999999062
0.9999999999980838
1.000000000007918
0.99999999975017
1.0000000022898672

Try it online!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading