Hi Murphy Lee,
As Brian said, it is very difficult as they are so similar and a lot of the time interchangeable. However; what you are looking at is a noun and a verb although they both seem like verbs.
In the S1, the person is saying it is "necessary for the understanding of the story". They are using the noun here, not the continuous gerund (-ing) as used with verbs. The same applies to your example in S2. You can change this to "necessary to understand" and it will mean the same thing.
If we take a look at S3, you are using the verb (re: “necessary to prevent such outbreaks"). Just like before, we can change the verb to be a noun and say "necessary for the prevention of such outbreaks" and it will mean the same thing.
In S4, " to ensure" cannot switch to be a noun as easily but you could say something like "“necessary for the certainty that the powers are used properly." but that is a little unnatural and I would use "to ensure" instead.
Overall, there is no actually difference in the meaning. You were just confused because the nouns look like continuous verbs. It's a common issue in English so I wouldn't worry about it too much!
If you have any further questions, please don't hesitate to get in touch www.italki.com/maddie.