Write a program to draw a text-based graph of a mathematical function f(x). Use
ID: 652118 • Letter: W
Question
Write a program to draw a text-based graph of a mathematical function f(x). Use axis limits of -10 to 10 and only plot discrete points i.e. points with integer value ordinates.
Sample I/O:
Enter a function f(x):
x+2
please see picture
Use nested loops to print the entire area of the graph (i.e. an outer loop for rows and an inner one for columns), keeping track of the current x and y values. Whenever the (rounded) value of the function f(x), entered by the user, is equal to the current y value, output "o" (small letter Oh), otherwise, output either the appropriate axis character or a space.
NOTE: Remember to import math to enable the use of some mathematical functions. How should the program support the entering of arbitrary functions?
? Obtain user input in the form of a string, then within the inner loop,
? whenever f(x) is to be calculated, use the Python
Explanation / Answer
Code
#!/usr/bin/env python2
"""
grph.py
"""
#_____________________________________________________________________________
# Imports
#
from math import sin, cos, tan
import os
import sys
#_____________________________________________________________________________
# Functions
#
def fprintf(fstream, fmt, *args):
"""
Emulate C's fprintf() function.
"""
fmt %= args
fstream.write(fmt)
return len(fmt)
def plot(x_expression, xmin, xmax, ymin, ymax):
"""
plot(str, int, int, int, int) -> str
Return a string representation of a graph of x_expression.
BUGS:
- The graph is inverted.
- Zero Divison Error when expressions like `1/x` are passed as
x_expression.
"""
return ' '.join(
''.join((
lambda x,y: 'o' if round(eval(x_expression)) == y else (
' ' if y != 0 and x != 0 else (
'|' if y != 0 and x == 0 else (
'-' if y == 0 and x != 0 else
'+' ))))
(x,y)
for x in xrange(xmax, xmin-1, -1))
for y in xrange(ymax, ymin-1, -1))
#_____________________________________________________________________________
# Main function
#
def main():
x_expression = raw_input("f(x) = ")
fprintf(sys.stdout, " Graph of f(x) = %s %s ",
x_expression,
plot(x_expression, -10, 10, -10, 10))
return 0
if __name__ == '__main__':
main()
# =================
Sample Test case:
stdin
copy
stdout
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.