Every pokemon has a base capture rate. For legendaries, it is typically 2% (Mewtwo is 6%).
Basically every action above the norm (just hitting the pokemon with the ball), increases the chance to catch it. The better the throw (including curve balls), the better the berry, and the better the medal, the greater the chance improves.
Based on the base capture rate of 2%, accomplishing everything possible perfectly only increases the capture rate to about 15%. So, no matter if you're the best ball thrower in the world and have the right berries and medals, there's always a chance to fail.
Sometimes the numbers are in your favour, sometimes they are not. This is basically RNG.