简体   繁体   中英

ValueError: x and y must have same first dimension, but have shapes (50,) and (1, 50)/ Multiprocessing

I am new to multiprocessing and plotting so I wished to make a code that could multi-process a range of heights to get the optimum launch angle for each height through an equation, then plot the results.

My main issue is when attempting to plot the results I run into an error. My secondary issue is by investigating my code for a while, now I'm beginning to think the multi-process is redundant? I still desire to use a multi-process. So any help in regards to that is also appreciated.

The equation seems to work fine when I don't wish to plot the results. But when I attempt to plot them I get "ValueError: x and y must have same first dimension, but have shapes (50,) and (1, 50)" which I don't exactly understand. I thought they were both just ranges to 50?

I've been messing around with it for a while attempting to get it to work. I believe its in the "list_h = np.array(range(1))" line since it just doesn't seem right. But that range seems to just repeat the results if I increase it. leading me to think I've structured this multi-process poorly.

My code is as follows

import numpy as np
from multiprocessing import Pool
import matplotlib.pyplot as plt

def f(x):
    speed = 5
    ran0 = (speed*speed)/9.8
    array_hght = np.array(range(50))
    return ((np.arccos(array_hght/(array_hght+ran0)))/2)*(180/np.pi)

if __name__ == '__main__':
    with Pool(5) as p:
        list_h = np.array(range(1))
        list_angles = p.map(f, list_h)
        print(list_angles)
        array_h = np.array(range(50))
        plt.plot(array_h, list_angles)
        plt.show()

Any help is greatly appreciated:).

You're almost there!! The pool.map() method returns the result in a list-form by applying f over the given input which is list_h in this case. Since list_h has only one item, then the result will be a list of just one value.

So, all you need to do is to get the first element from list_angles like so:

if __name__ == '__main__':
    with Pool(5) as p:
        list_h = np.array(range(1))
        list_angles = p.map(f, list_h)[0]    #<--- HERE
        array_h = np.array(range(50))
        print(array_h.shape)
        plt.plot(array_h, list_angles)
        plt.show()

And running the previous code will results in the following graph: 在此处输入图像描述

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