Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Tuesday, May 7, 2013

Nested Loop: Trigonometric Functions


Problem: Plot the given trigonometric function.

Example:


trignometry_plot(fn=math.sin, plot_char="#")
                                        #
                                              #
                                                    #
                                                         #
                                                              #
                                                                 #
                                                                    #
                                                                     #
                                                                     #
                                                                    #
                                                                 #
                                                              #
                                                         #
                                                    #
                                              #
                                        #
                                 #
                           #
                      #
                 #
              #
           #
          #
          #
           #
              #
                 #
                      #
                           #
                                 #
                                       #



Solution in Python:


import math

def trignometry_plot(fn=math.sin, n_x_steps=30, y_orig=40,
                     y_range=30, plot_char="."):
    """
    Author: Mayur P Srivastava
    """

    pi = 3.14159

    for xi in range(n_x_steps+1):
        x = 2 * pi / n_x_steps * xi
        y = y_orig + y_range * fn(x)
        row = ""
        if y >= 0:
            for i in range(y):
                row += " "
            row += plot_char

        print row



Concepts Learned: Nested loops, trigonometric functions.

No comments:

Post a Comment