/
graphing-calculator.py
226 lines (180 loc) · 6.44 KB
/
graphing-calculator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
from contextlib import nullcontext
from statistics import LinearRegression, linear_regression
from tkinter import Variable
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
operator1 = [1]
operator2 = [2]
operator3 = [3]
data_point_list_x = []
data_point_list_y = []
addition = ['+']
subtraction = ['-']
multiplication = ['*']
division = ['/']
exponentiation = ['^']
stop = ['done']
ys = []
print("Welcome to the graphing calculator!")
print("the following operations are supported:")
print("1. linear regression")
print("2. plot a graph")
print("3. graph a function")
input("Press enter to continue...")
operation = input("Enter in the operation you want to perform: ")
try:
operation = int(operation)
except ValueError:
print("You have to type a number!")
exit()
if int(operation) in operator1 or operator2 or operator3:
if operation == 1:
print("Enter the x value, then the y value after pressing enter each time")
print("up to 10 data points are allowed")
print("if you want to stop entering data points, type 'done'")
input("Press enter to continue...")
number = 0
i = 1
while i < 11:
number = int(number) + 1
data_point_x = input("Enter the x value for your first data point: ")
try:
data_point_x = float(data_point_x)
except ValueError:
print("You have to type a number!")
exit()
data_point_list_x.append(data_point_x)
data_point_y = input("Enter the y value for your first data point: ")
try:
data_point_y = float(data_point_y)
except ValueError:
print("You have to type a number!")
exit()
data_point_list_y.append(data_point_y)
stop1 = input("Press enter to continue or done to stop...")
if stop1 in stop:
i = 11
i = int(i) + 1
print("The data points you entered: ")
print(data_point_list_x)
print(data_point_list_y)
input("Press enter to continue...")
elif operation == 2:
print("Enter a function solving for y")
print("Put NO spaces in the function")
print("If x has no coefficient, put 1")
print("Example: y=2x+3")
input("Press enter to continue...")
function = input("Type in your function: ")
# 100 linearly spaced numbers
x = np.linspace(-5,5,100)
# the function, which is y = x^2 here
try:
'y' and '=' in function
except:
print("Enter a valid function try again ")
exit()
index = 2
i = 0
while i == 0:
try:
float(function[index])
except:
i=1
index = index + 1
def operatorReaction(x):
if function[index] in addition:
y_value = x + float(function[index+1])
ys.append(y_value)
elif function[index] in subtraction:
y_value = x - float(function[index+1])
ys.append(y_value)
else:
print("Enter a valid function try again! ")
exit()
def operatorReaction2(x):
if function[index] in multiplication:
y_value = x * float(function[index+1])
ys.append(y_value)
elif function[index] in division:
y_value = x / float(function[index+1])
ys.append(y_value)
elif function[index] in exponentiation:
y_value = x ** float(function[index+1])
ys.append(y_value)
try:
float(function[2])
except:
print("Enter a valid function try again. ")
exit()
x = float(function[2])*x
posOfX = function.rfind('x')
#coefficient = function[posOfX - 1]
operatorReaction(x)
operatorReaction2(x)
def estimate_coef(x, y):
# number of observations/points
n = np.size(x)
# mean of x and y vector
m_x = np.mean(x)
m_y = np.mean(y)
# calculating cross-deviation and deviation about x
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
# calculating regression coefficients
b_1 = SS_xy / SS_xx
b_0 = m_y - b_1*m_x
return (b_0, b_1)
def plot_regression_line(x, y, b):
# plotting the actual points as scatter plot
plt.scatter(x, y, color="m",
marker="o", s=30)
# predicted response vector
y_pred = b[0] + b[1]*x
# plotting the regression line
plt.plot(x, y_pred, color="g")
# putting labels
plt.xlabel('x')
plt.ylabel('y')
# function to show plot
plt.show()
def main():
# observations / data
x = np.array(data_point_list_x)
y = np.array(data_point_list_y)
# estimating coefficients
b = estimate_coef(x, y)
element = "Estimated coefficients:\nb_0 = {} \
\nb_1 = {}".format(b[0] , b[1])
print(element)
with open('Log.txt', 'a') as f:
f.write(element)
# plotting regression line
plot_regression_line(x, y, b)
if __name__ == "__main__":
main()
#print(x)
#print(ys)
# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# plot the function
vector = np.vectorize(np.int_)
xr = np.array(x)
xs = xr.astype(float)
yr =np.array(ys)
y = yr.astype(float)
ys = np.reshape(y , (100, 1))
plt.plot(xs ,ys, 'r')
# show the plot
plt.show()
else:
print("You have to type an operation!?")
exit()