Python loglog graph











up vote
1
down vote

favorite












In the following code I have implemented composite Simpsons Rule in python. I have tested it by integrating f = sinx over [0,pi/2] and plotting the resulting absolute error as a function of n for a suitable range of integer values for n. As shown below. Now I am trying to verify that my method is of order 4. To do this instead of plotting the error vs n I need to plot n vs n^(-4) to show that both have the same slope.



from math import pi, cos, sin
from matplotlib import pyplot as plt


def simpson(f, a, b, n):
"""Approximates the definite integral of f from a to b by the composite Simpson's rule, using 2n subintervals """

h = (b - a) / (2*n)
s = f(a) + f(b)


for i in range(1, 2*n, 2):
s += 4 * f(a + i * h)
for i in range(2, 2*n-1, 2):
s += 2 * f(a + i * h)
return s * h / 3


diffs = {}
exact = 1 - cos(pi/2)
for n in range(1, 100):
result = simpson(lambda x: sin(x), 0.0, pi/2, n)
diffs[2*n] = abs(exact - result) # use 2*n or n here, your choice.


ordered = sorted(diffs.items())
x,y = zip(*ordered)
plt.autoscale()
plt.loglog(x,y)
plt.xlabel("Intervals")
plt.ylabel("Error")
plt.show()


this results in my error graph:



enter image description here










share|improve this question


























    up vote
    1
    down vote

    favorite












    In the following code I have implemented composite Simpsons Rule in python. I have tested it by integrating f = sinx over [0,pi/2] and plotting the resulting absolute error as a function of n for a suitable range of integer values for n. As shown below. Now I am trying to verify that my method is of order 4. To do this instead of plotting the error vs n I need to plot n vs n^(-4) to show that both have the same slope.



    from math import pi, cos, sin
    from matplotlib import pyplot as plt


    def simpson(f, a, b, n):
    """Approximates the definite integral of f from a to b by the composite Simpson's rule, using 2n subintervals """

    h = (b - a) / (2*n)
    s = f(a) + f(b)


    for i in range(1, 2*n, 2):
    s += 4 * f(a + i * h)
    for i in range(2, 2*n-1, 2):
    s += 2 * f(a + i * h)
    return s * h / 3


    diffs = {}
    exact = 1 - cos(pi/2)
    for n in range(1, 100):
    result = simpson(lambda x: sin(x), 0.0, pi/2, n)
    diffs[2*n] = abs(exact - result) # use 2*n or n here, your choice.


    ordered = sorted(diffs.items())
    x,y = zip(*ordered)
    plt.autoscale()
    plt.loglog(x,y)
    plt.xlabel("Intervals")
    plt.ylabel("Error")
    plt.show()


    this results in my error graph:



    enter image description here










    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      In the following code I have implemented composite Simpsons Rule in python. I have tested it by integrating f = sinx over [0,pi/2] and plotting the resulting absolute error as a function of n for a suitable range of integer values for n. As shown below. Now I am trying to verify that my method is of order 4. To do this instead of plotting the error vs n I need to plot n vs n^(-4) to show that both have the same slope.



      from math import pi, cos, sin
      from matplotlib import pyplot as plt


      def simpson(f, a, b, n):
      """Approximates the definite integral of f from a to b by the composite Simpson's rule, using 2n subintervals """

      h = (b - a) / (2*n)
      s = f(a) + f(b)


      for i in range(1, 2*n, 2):
      s += 4 * f(a + i * h)
      for i in range(2, 2*n-1, 2):
      s += 2 * f(a + i * h)
      return s * h / 3


      diffs = {}
      exact = 1 - cos(pi/2)
      for n in range(1, 100):
      result = simpson(lambda x: sin(x), 0.0, pi/2, n)
      diffs[2*n] = abs(exact - result) # use 2*n or n here, your choice.


      ordered = sorted(diffs.items())
      x,y = zip(*ordered)
      plt.autoscale()
      plt.loglog(x,y)
      plt.xlabel("Intervals")
      plt.ylabel("Error")
      plt.show()


      this results in my error graph:



      enter image description here










      share|improve this question













      In the following code I have implemented composite Simpsons Rule in python. I have tested it by integrating f = sinx over [0,pi/2] and plotting the resulting absolute error as a function of n for a suitable range of integer values for n. As shown below. Now I am trying to verify that my method is of order 4. To do this instead of plotting the error vs n I need to plot n vs n^(-4) to show that both have the same slope.



      from math import pi, cos, sin
      from matplotlib import pyplot as plt


      def simpson(f, a, b, n):
      """Approximates the definite integral of f from a to b by the composite Simpson's rule, using 2n subintervals """

      h = (b - a) / (2*n)
      s = f(a) + f(b)


      for i in range(1, 2*n, 2):
      s += 4 * f(a + i * h)
      for i in range(2, 2*n-1, 2):
      s += 2 * f(a + i * h)
      return s * h / 3


      diffs = {}
      exact = 1 - cos(pi/2)
      for n in range(1, 100):
      result = simpson(lambda x: sin(x), 0.0, pi/2, n)
      diffs[2*n] = abs(exact - result) # use 2*n or n here, your choice.


      ordered = sorted(diffs.items())
      x,y = zip(*ordered)
      plt.autoscale()
      plt.loglog(x,y)
      plt.xlabel("Intervals")
      plt.ylabel("Error")
      plt.show()


      this results in my error graph:



      enter image description here







      python






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 at 19:16









      fr14

      1277




      1277
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          You can add another line to your plot by making another call to plt.loglog(). So just before your plt.show() you can add:



          n = 
          n_inv_4 =
          for i in range(1,100):
          n.append(2*i)
          n_inv_4.append(1.0 / ((2*i)**4))
          plt.loglog(n, n_inv_4)


          Note that the above calculations use (2*i) to match the (2*n) used in the simpson method.






          share|improve this answer





















          • how would I include an index to show which line is which?
            – fr14
            Nov 19 at 19:50










          • Getting your moneys worth out of this :-) The calls to plt.loglog return a list of lines that it plots. You can use that return to create a legend. So, replace plt.loglog(x,y) with error_lines = plt.loglog(x,y), and replace plt.loglog(n, n_inv_4) with n_lines = plt.loglog(n, n_inv_4). Then create the legend by adding plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), 'upper right') just before the plt.show(). The 'upper right' specifies where to put the legend.
            – John Anderson
            Nov 19 at 20:09










          • I am getting an error in the plt.figlegend saying 'text' obect does not support indexing
            – fr14
            Nov 19 at 20:31










          • was there a bracket missing or one needed to be added?
            – fr14
            Nov 19 at 20:37










          • The only indexing going on is the error_lines[0] and the n_lines[0]. Both error_lines and n_lines should be lists of lines returned by plt.loglog. Are you sure you replaced the calls to plt.loglog correctly?
            – John Anderson
            Nov 20 at 2:00













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381215%2fpython-loglog-graph%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          You can add another line to your plot by making another call to plt.loglog(). So just before your plt.show() you can add:



          n = 
          n_inv_4 =
          for i in range(1,100):
          n.append(2*i)
          n_inv_4.append(1.0 / ((2*i)**4))
          plt.loglog(n, n_inv_4)


          Note that the above calculations use (2*i) to match the (2*n) used in the simpson method.






          share|improve this answer





















          • how would I include an index to show which line is which?
            – fr14
            Nov 19 at 19:50










          • Getting your moneys worth out of this :-) The calls to plt.loglog return a list of lines that it plots. You can use that return to create a legend. So, replace plt.loglog(x,y) with error_lines = plt.loglog(x,y), and replace plt.loglog(n, n_inv_4) with n_lines = plt.loglog(n, n_inv_4). Then create the legend by adding plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), 'upper right') just before the plt.show(). The 'upper right' specifies where to put the legend.
            – John Anderson
            Nov 19 at 20:09










          • I am getting an error in the plt.figlegend saying 'text' obect does not support indexing
            – fr14
            Nov 19 at 20:31










          • was there a bracket missing or one needed to be added?
            – fr14
            Nov 19 at 20:37










          • The only indexing going on is the error_lines[0] and the n_lines[0]. Both error_lines and n_lines should be lists of lines returned by plt.loglog. Are you sure you replaced the calls to plt.loglog correctly?
            – John Anderson
            Nov 20 at 2:00

















          up vote
          1
          down vote



          accepted










          You can add another line to your plot by making another call to plt.loglog(). So just before your plt.show() you can add:



          n = 
          n_inv_4 =
          for i in range(1,100):
          n.append(2*i)
          n_inv_4.append(1.0 / ((2*i)**4))
          plt.loglog(n, n_inv_4)


          Note that the above calculations use (2*i) to match the (2*n) used in the simpson method.






          share|improve this answer





















          • how would I include an index to show which line is which?
            – fr14
            Nov 19 at 19:50










          • Getting your moneys worth out of this :-) The calls to plt.loglog return a list of lines that it plots. You can use that return to create a legend. So, replace plt.loglog(x,y) with error_lines = plt.loglog(x,y), and replace plt.loglog(n, n_inv_4) with n_lines = plt.loglog(n, n_inv_4). Then create the legend by adding plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), 'upper right') just before the plt.show(). The 'upper right' specifies where to put the legend.
            – John Anderson
            Nov 19 at 20:09










          • I am getting an error in the plt.figlegend saying 'text' obect does not support indexing
            – fr14
            Nov 19 at 20:31










          • was there a bracket missing or one needed to be added?
            – fr14
            Nov 19 at 20:37










          • The only indexing going on is the error_lines[0] and the n_lines[0]. Both error_lines and n_lines should be lists of lines returned by plt.loglog. Are you sure you replaced the calls to plt.loglog correctly?
            – John Anderson
            Nov 20 at 2:00















          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          You can add another line to your plot by making another call to plt.loglog(). So just before your plt.show() you can add:



          n = 
          n_inv_4 =
          for i in range(1,100):
          n.append(2*i)
          n_inv_4.append(1.0 / ((2*i)**4))
          plt.loglog(n, n_inv_4)


          Note that the above calculations use (2*i) to match the (2*n) used in the simpson method.






          share|improve this answer












          You can add another line to your plot by making another call to plt.loglog(). So just before your plt.show() you can add:



          n = 
          n_inv_4 =
          for i in range(1,100):
          n.append(2*i)
          n_inv_4.append(1.0 / ((2*i)**4))
          plt.loglog(n, n_inv_4)


          Note that the above calculations use (2*i) to match the (2*n) used in the simpson method.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 at 19:41









          John Anderson

          2,0731312




          2,0731312












          • how would I include an index to show which line is which?
            – fr14
            Nov 19 at 19:50










          • Getting your moneys worth out of this :-) The calls to plt.loglog return a list of lines that it plots. You can use that return to create a legend. So, replace plt.loglog(x,y) with error_lines = plt.loglog(x,y), and replace plt.loglog(n, n_inv_4) with n_lines = plt.loglog(n, n_inv_4). Then create the legend by adding plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), 'upper right') just before the plt.show(). The 'upper right' specifies where to put the legend.
            – John Anderson
            Nov 19 at 20:09










          • I am getting an error in the plt.figlegend saying 'text' obect does not support indexing
            – fr14
            Nov 19 at 20:31










          • was there a bracket missing or one needed to be added?
            – fr14
            Nov 19 at 20:37










          • The only indexing going on is the error_lines[0] and the n_lines[0]. Both error_lines and n_lines should be lists of lines returned by plt.loglog. Are you sure you replaced the calls to plt.loglog correctly?
            – John Anderson
            Nov 20 at 2:00




















          • how would I include an index to show which line is which?
            – fr14
            Nov 19 at 19:50










          • Getting your moneys worth out of this :-) The calls to plt.loglog return a list of lines that it plots. You can use that return to create a legend. So, replace plt.loglog(x,y) with error_lines = plt.loglog(x,y), and replace plt.loglog(n, n_inv_4) with n_lines = plt.loglog(n, n_inv_4). Then create the legend by adding plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), 'upper right') just before the plt.show(). The 'upper right' specifies where to put the legend.
            – John Anderson
            Nov 19 at 20:09










          • I am getting an error in the plt.figlegend saying 'text' obect does not support indexing
            – fr14
            Nov 19 at 20:31










          • was there a bracket missing or one needed to be added?
            – fr14
            Nov 19 at 20:37










          • The only indexing going on is the error_lines[0] and the n_lines[0]. Both error_lines and n_lines should be lists of lines returned by plt.loglog. Are you sure you replaced the calls to plt.loglog correctly?
            – John Anderson
            Nov 20 at 2:00


















          how would I include an index to show which line is which?
          – fr14
          Nov 19 at 19:50




          how would I include an index to show which line is which?
          – fr14
          Nov 19 at 19:50












          Getting your moneys worth out of this :-) The calls to plt.loglog return a list of lines that it plots. You can use that return to create a legend. So, replace plt.loglog(x,y) with error_lines = plt.loglog(x,y), and replace plt.loglog(n, n_inv_4) with n_lines = plt.loglog(n, n_inv_4). Then create the legend by adding plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), 'upper right') just before the plt.show(). The 'upper right' specifies where to put the legend.
          – John Anderson
          Nov 19 at 20:09




          Getting your moneys worth out of this :-) The calls to plt.loglog return a list of lines that it plots. You can use that return to create a legend. So, replace plt.loglog(x,y) with error_lines = plt.loglog(x,y), and replace plt.loglog(n, n_inv_4) with n_lines = plt.loglog(n, n_inv_4). Then create the legend by adding plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), 'upper right') just before the plt.show(). The 'upper right' specifies where to put the legend.
          – John Anderson
          Nov 19 at 20:09












          I am getting an error in the plt.figlegend saying 'text' obect does not support indexing
          – fr14
          Nov 19 at 20:31




          I am getting an error in the plt.figlegend saying 'text' obect does not support indexing
          – fr14
          Nov 19 at 20:31












          was there a bracket missing or one needed to be added?
          – fr14
          Nov 19 at 20:37




          was there a bracket missing or one needed to be added?
          – fr14
          Nov 19 at 20:37












          The only indexing going on is the error_lines[0] and the n_lines[0]. Both error_lines and n_lines should be lists of lines returned by plt.loglog. Are you sure you replaced the calls to plt.loglog correctly?
          – John Anderson
          Nov 20 at 2:00






          The only indexing going on is the error_lines[0] and the n_lines[0]. Both error_lines and n_lines should be lists of lines returned by plt.loglog. Are you sure you replaced the calls to plt.loglog correctly?
          – John Anderson
          Nov 20 at 2:00




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381215%2fpython-loglog-graph%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'