-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
977 lines (810 loc) · 34 KB
/
main.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends._backend_tk import NavigationToolbar2Tk
from math import *
import random as rnd
from sympy import *
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.lib.utils import ImageReader
import datetime
import os
import io
import re
class App(ttk.Frame):
# Construction method
def __init__(self, parent):
ttk.Frame.__init__(self)
# Make the app responsive
for index in [0, 1, 2]:
self.columnconfigure(index=index, weight=1)
self.rowconfigure(index=index, weight=1)
# Create control variables for checkboxes
self.tanteoVar = tk.BooleanVar()
self.biseccionVar = tk.BooleanVar()
self.reglaFalsaVar = tk.BooleanVar()
self.nRVar = tk.BooleanVar()
self.secanteVar = tk.BooleanVar()
self.steffensenVar = tk.BooleanVar()
# Create widgets
self.setup_widgets()
# Function to setup widgets on the app
def setup_widgets(self):
# Equation Entry Frame
self.entryFrame = ttk.LabelFrame(
self, text="Enter the equation", padding=(20, 10)
)
self.entryFrame.grid(row=0, column=0, padx=20, pady=10, sticky="nsew")
self.entryFrame.columnconfigure(index=0, weight=1)
# Equation Entry
self.eqEntry = ttk.Entry(self.entryFrame)
self.eqEntry.grid(row=0, column=0, padx=5, pady=(10, 10), sticky="ew")
# Derivative Equation
self.derivativeEntry = ttk.Entry(self.entryFrame)
self.derivativeEntry.grid(row=1, column=0, padx=5, pady=(10, 10), sticky="ew")
# set a placeholder text
self.derivativeEntry.insert(0, "Derivative Equation")
# make the Entry widget uneditable
self.derivativeEntry.configure(state="disabled")
# set the font of the Entry widget to have reduced opacity and italicized text
self.derivativeEntry.configure(font=("", 9, "italic"), foreground="#BBBBBB")
# Create a Frame for the Checkbuttons
self.check_frame = ttk.LabelFrame(
self, text="Chose the method", padding=(20, 10)
)
self.check_frame.grid(row=1, column=0, padx=20, pady=10, sticky="nsew")
# Checkbuttons
self.tanteoCheck = ttk.Checkbutton(
self.check_frame, text="T&E", variable=self.tanteoVar
)
self.tanteoCheck.grid(row=0, column=0, padx=5, pady=10, sticky="nsew")
self.biseccionCheck = ttk.Checkbutton(
self.check_frame, text="Bisection", variable=self.biseccionVar
)
self.biseccionCheck.grid(row=0, column=1, padx=5, pady=10, sticky="nsew")
self.reglaFalsaCheck = ttk.Checkbutton(
self.check_frame, text="Regula Falsi", variable=self.reglaFalsaVar
)
self.reglaFalsaCheck.grid(row=0, column=2, padx=5, pady=10, sticky="nsew")
self.nRCheck = ttk.Checkbutton(
self.check_frame, text="N. R", variable=self.nRVar
)
self.nRCheck.grid(row=1, column=0, padx=5, pady=10, sticky="nsew")
self.secanteCheck = ttk.Checkbutton(
self.check_frame, text="Secant", variable=self.secanteVar
)
self.secanteCheck.grid(row=1, column=1, padx=5, pady=10, sticky="nsew")
self.steffensenCheck = ttk.Checkbutton(
self.check_frame, text="Steffensen", variable=self.steffensenVar
)
self.steffensenCheck.grid(row=1, column=2, padx=5, pady=10, sticky="nsew")
# Method, Answers and Iteration Frame
self.answersFrame = ttk.LabelFrame(
self,
text=" Method Answers Avg. Iterations ",
padding=(20, 10),
)
self.answersFrame.grid(row=2, column=0, padx=20, pady=10, sticky="nsew")
# Method Label
self.tanteoLabel = ttk.Label(self.answersFrame, text="T&E")
self.tanteoLabel.grid(row=0, column=0, pady=10, columnspan=2, sticky="nsew")
self.biseccionLabel = ttk.Label(self.answersFrame, text="Bisection")
self.biseccionLabel.grid(row=1, column=0, pady=10, columnspan=2, sticky="nsew")
self.reglaFalsaLabel = ttk.Label(self.answersFrame, text="R. Falsi")
self.reglaFalsaLabel.grid(row=2, column=0, pady=10, columnspan=2, sticky="nsew")
self.nRLabel = ttk.Label(self.answersFrame, text="N. R")
self.nRLabel.grid(row=3, column=0, pady=10, columnspan=2, sticky="nsew")
self.secanteLabel = ttk.Label(self.answersFrame, text="Secant")
self.secanteLabel.grid(row=4, column=0, pady=10, columnspan=2, sticky="nsew")
self.steffensenLabel = ttk.Label(self.answersFrame, text="Steffensen")
self.steffensenLabel.grid(row=5, column=0, pady=10, columnspan=2, sticky="nsew")
# Inside Answer Frame
self.insideAnswerFrame = ttk.Frame(self.answersFrame)
self.insideAnswerFrame.grid(row=0, column=2, padx=10, sticky="nsew", rowspan=7)
self.insideAnswerFrame.columnconfigure(index=0, weight=1)
# Answer Outputs
self.tanteoOutput = ttk.Entry(self.insideAnswerFrame, width=20)
self.tanteoOutput.grid(row=0, column=0, padx=(10, 0), pady=(8, 0), sticky="ew")
self.tanteoIterationsOutput = ttk.Entry(self.insideAnswerFrame, width=13)
self.tanteoIterationsOutput.grid(
row=0, column=1, padx=(10, 0), pady=(10, 0), sticky="ew"
)
self.biseccionOutput = ttk.Entry(self.insideAnswerFrame, width=20)
self.biseccionOutput.grid(
row=1, column=0, padx=(10, 0), pady=(8, 0), sticky="ew"
)
self.biseccionIterationsOutput = ttk.Entry(self.insideAnswerFrame, width=10)
self.biseccionIterationsOutput.grid(
row=1, column=1, padx=(10, 0), pady=(8, 0), sticky="ew"
)
self.reglaFalsaOutput = ttk.Entry(self.insideAnswerFrame, width=20)
self.reglaFalsaOutput.grid(
row=2, column=0, padx=(10, 0), pady=(8, 0), sticky="ew"
)
self.reglaFalsaIterationsOutput = ttk.Entry(self.insideAnswerFrame, width=10)
self.reglaFalsaIterationsOutput.grid(
row=2, column=1, padx=(10, 0), pady=(8, 0), sticky="ew"
)
self.nROutput = ttk.Entry(self.insideAnswerFrame, width=20)
self.nROutput.grid(row=3, column=0, padx=(10, 0), pady=(8, 0), sticky="ew")
self.nRIterationsOutput = ttk.Entry(self.insideAnswerFrame, width=10)
self.nRIterationsOutput.grid(
row=3, column=1, padx=(10, 0), pady=(8, 0), sticky="ew"
)
self.secanteOutput = ttk.Entry(self.insideAnswerFrame, width=20)
self.secanteOutput.grid(row=4, column=0, padx=(10, 0), pady=(8, 0), sticky="ew")
self.secanteIterationsOutput = ttk.Entry(self.insideAnswerFrame, width=10)
self.secanteIterationsOutput.grid(
row=4, column=1, padx=(10, 0), pady=(8, 0), sticky="ew"
)
self.steffensenOutput = ttk.Entry(self.insideAnswerFrame, width=20)
self.steffensenOutput.grid(
row=6, column=0, padx=(10, 0), pady=(8, 0), sticky="ew"
)
self.steffensenIterationsOutput = ttk.Entry(self.insideAnswerFrame, width=10)
self.steffensenIterationsOutput.grid(
row=6, column=1, padx=(10, 0), pady=(8, 0), sticky="ew"
)
# Solve Button
self.buttonFrame = ttk.Frame(self)
self.buttonFrame.grid(row=3, column=0, padx=20, pady=(5, 20), sticky="nsew")
self.buttonFrame.columnconfigure(index=0, weight=1)
self.buttonFrame.columnconfigure(index=1, weight=1)
self.solveButton = ttk.Button(
self.buttonFrame,
text="Solve",
style="Accent.TButton",
command=self.solve,
)
self.solveButton.grid(row=0, column=0, padx=0, pady=0, sticky="nsew")
# Report button
self.reportButton = ttk.Button(
self.buttonFrame,
text="Report",
style="Accent.TButton",
command=self.getReport,
)
self.reportButton.grid(row=0, column=1, padx=(5, 0), pady=0, sticky="nsew")
# Graph Frame
self.graphFrame = ttk.Frame(self)
self.graphFrame.grid(row=0, column=1, padx=(0, 20), pady=(25, 10), rowspan=5)
# Graph
self.fig = Figure(figsize=(4.7, 5.6), dpi=100)
self.ax = self.fig.add_subplot(111)
self.fig.tight_layout()
self.canvas = FigureCanvasTkAgg(self.fig, master=self.graphFrame)
# Setting the predefined zoom
self.ax.set_xlim(-20, 20)
self.ax.set_ylim(-20, 20)
# Drawing the canvas
self.canvas.draw()
self.canvas.get_tk_widget().grid(row=0, column=0, sticky="nsew")
# Drawing x and y axes
self.ax.axhline(0, color="black", linewidth="1.5")
self.ax.axvline(0, color="black", linewidth="1.5")
# Navigation Bar
self.tlb = NavigationToolbar2Tk(
self.canvas, self.graphFrame, pack_toolbar=False
)
self.tlb.update()
self.tlb.grid(row=1, column=0, sticky="nsew")
# Connecting the scrolling action
self.fig.canvas.mpl_connect("scroll_event", self.on_scroll)
# Set the cross as the initial element
self.tlb.pan()
# Function to scroll with the mouse
def on_scroll(self, event):
# Get limits
xlim = self.ax.get_xlim()
ylim = self.ax.get_ylim()
# Calculate scroll limits
if event.button == "up":
# Zoom in
x_center = (xlim[0] + xlim[1]) / 2
y_center = (ylim[0] + ylim[1]) / 2
x_range = (xlim[1] - xlim[0]) / 2
y_range = (ylim[1] - ylim[0]) / 2
self.ax.set_xlim(x_center - x_range / 2, x_center + x_range / 2)
self.ax.set_ylim(y_center - y_range / 2, y_center + y_range / 2)
elif event.button == "down":
# Zoom out
x_center = (xlim[0] + xlim[1]) / 2
y_center = (ylim[0] + ylim[1]) / 2
x_range = (xlim[1] - xlim[0]) * 2
y_range = (ylim[1] - ylim[0]) * 2
self.ax.set_xlim(x_center - x_range / 2, x_center + x_range / 2)
self.ax.set_ylim(y_center - y_range / 2, y_center + y_range / 2)
self.fig.canvas.draw()
# Mother function bound to the button
def solve(self):
self.solveButton.config(state=tk.DISABLED)
self.reportButton.config(state=tk.DISABLED)
self.tanteoCheck.config(state=tk.DISABLED)
self.biseccionCheck.config(state=tk.DISABLED)
self.reglaFalsaCheck.config(state=tk.DISABLED)
self.nRCheck.config(state=tk.DISABLED)
self.secanteCheck.config(state=tk.DISABLED)
self.steffensenCheck.config(state=tk.DISABLED)
self.popup = self.show_popup()
# Get the entry
eqVar, degree = self.getEntry()
# Check if there is something on the entry
if eqVar is not None and eqVar != "":
self.checked()
self.getGraphic(eqVar)
self.popup.destroy()
self.solveButton.config(state=tk.NORMAL)
self.reportButton.config(state=tk.NORMAL)
self.tanteoCheck.config(state=tk.NORMAL)
self.biseccionCheck.config(state=tk.NORMAL)
self.reglaFalsaCheck.config(state=tk.NORMAL)
self.nRCheck.config(state=tk.NORMAL)
self.secanteCheck.config(state=tk.NORMAL)
self.steffensenCheck.config(state=tk.NORMAL)
# Show a loading popup
def show_popup(self):
self.popup = tk.Toplevel()
self.popup.title("Loading...")
self.popup.geometry("200x100")
ttk.Label(self.popup, text="Loading...").pack(pady=10)
ttk.Progressbar(self.popup, mode="indeterminate").pack(pady=10)
self.popup.transient(master=self)
self.popup.grab_set()
self.popup.update()
self.popup.minsize(self.popup.winfo_width(), self.popup.winfo_height())
x_cordinate = int(
(self.popup.winfo_screenwidth() / 2) - (self.popup.winfo_width() / 2)
)
y_cordinate = int(
(self.popup.winfo_screenheight() / 2) - (self.popup.winfo_height() / 2)
)
self.popup.geometry("+{}+{}".format(x_cordinate, y_cordinate - 20))
self.popup.update()
return self.popup
# Function to clear the entries
def cleanEntries(self):
# Reset states
self.tanteoOutput.configure(state="normal")
self.tanteoIterationsOutput.configure(state="normal")
self.tanteoOutput.delete(0, "end")
self.tanteoIterationsOutput.delete(0, "end")
self.biseccionOutput.configure(state="normal")
self.biseccionIterationsOutput.configure(state="normal")
self.biseccionOutput.delete(0, "end")
self.biseccionIterationsOutput.delete(0, "end")
self.reglaFalsaOutput.configure(state="normal")
self.reglaFalsaIterationsOutput.configure(state="normal")
self.reglaFalsaOutput.delete(0, "end")
self.reglaFalsaIterationsOutput.delete(0, "end")
self.nROutput.configure(state="normal")
self.nRIterationsOutput.configure(state="normal")
self.nROutput.delete(0, "end")
self.nRIterationsOutput.delete(0, "end")
self.secanteOutput.configure(state="normal")
self.secanteIterationsOutput.configure(state="normal")
self.secanteOutput.delete(0, "end")
self.secanteIterationsOutput.delete(0, "end")
self.steffensenOutput.configure(state="normal")
self.steffensenIterationsOutput.configure(state="normal")
self.steffensenOutput.delete(0, "end")
self.steffensenIterationsOutput.delete(0, "end")
# Function to check which function/s is/are selected
def checked(self):
# Reset states
self.cleanEntries()
if self.tanteoVar.get() == True:
self.tanteo()
if self.biseccionVar.get() == True:
self.biseccion()
if self.reglaFalsaVar.get() == True:
self.reglaFalsa()
if self.nRVar.get() == True:
self.newtonRaphson()
if self.secanteVar.get() == True:
self.secante()
if self.steffensenVar.get() == True:
self.steffensen()
# Function to get the entry equation
def getEntry(self):
# Get equation from entry box
rawEq = str(self.eqEntry.get())
# Change x for xI
eqVar = rawEq.replace("x", "xI").replace("X", "xI")
# Get equation degree
match = re.search(r"\*\*?\s*(\d+)", str(eqVar))
if match:
degree = int(match.group(1))
else:
degree = 1
if (degree % 2) == 0:
eqVar = re.sub(r"xI\*\*([02468])", r"abs(xI)**\1", eqVar)
return eqVar, degree
# Function to get the equation without wrapped it in absolute value
def getEntryRaw(self):
rawEq = str(self.eqEntry.get())
# Change x for xI
eqVar = rawEq.replace("x", "xI").replace("X", "xI")
return eqVar
# Function to generate the random numbers for biseccion and regla falsa
def rndNumbers(self, eqVar, roots):
xLow = rnd.randint(-10, 10)
while eval(eqVar, {"xI": xLow}) > 0 and xLow not in roots:
xLow = rnd.randint(-10, 10)
xHigh = rnd.randint(-10, 10)
while eval(eqVar, {"xI": xHigh}) < 0 and xHigh not in roots:
xHigh = rnd.randint(-10, 10)
return xLow, xHigh
# Function to get an integer seed
def getIntSeed(self, roots):
while True:
x0 = rnd.randint(-10, 10)
if x0 not in roots:
return x0
# Function to get a float seed
def getUniformSeed(self, roots):
while True:
x0 = rnd.uniform(-10, 10)
if x0 not in roots:
return x0
# Function to verify if the root is already in the array
def verifyRoots(self, roots, counters, num, count):
if round(num, 2) not in roots:
roots.append(round(num, 2))
counters.append(count)
# Function to clean the array from numbers that are to close
def cleanArray(self, arr, margin):
return sorted(
[arr[0]]
+ [arr[i] for i in range(1, len(arr)) if abs(arr[i] - arr[i - 1]) > margin]
)
# Function to print the answers in the UI
def giveAnswers(self, methodOutput, methodIterationsOutput, roots, counters):
averageCounter = sum(counters) / len(counters)
methodOutput.insert(0, sorted(roots))
methodOutput.configure(state="readonly")
methodIterationsOutput.insert(0, averageCounter)
methodIterationsOutput.configure(state="readonly")
# Function to get the derivative automatically
def getDerivative(self):
self.derivativeEntry.configure(state="enable")
self.derivativeEntry.delete(0, "end")
eqVarRaw = self.getEntryRaw()
x = symbols("xI")
sympify(eqVarRaw)
derivative = diff(eqVarRaw, x)
derivativeString = str(derivative)
self.derivativeEntry.insert(0, derivativeString.replace("xI", "x"))
self.derivativeEntry.configure(state="disable")
return derivativeString
def tanteo(self):
roots = []
counters = []
# Get equation entry
eqVar, degree = self.getEntry()
bigCount = 0
while len(roots) < degree:
bigCount += 1
counter = 0
# Generating random number
x1 = 0
xI = self.getIntSeed(roots)
if xI >= 0: # if xI is positive or zero
while True:
if eval(eqVar, {"xI": xI}) > 0:
counter += 1
x1 = xI - 0.001
xI = x1
elif eval(eqVar, {"xI": xI}) < 0:
counter += 1
x1 = xI + 0.001
if abs(eval(eqVar, {"xI": xI})) <= 0.0001:
self.verifyRoots(roots, counters, xI, counter)
break
if counter > 1000:
break
else: # if xI is negative
while True:
if eval(eqVar, {"xI": xI}) > 0:
counter += 1
x1 = xI + 0.001
xI = x1
elif eval(eqVar, {"xI": xI}) < 0:
counter += 1
x1 = xI - 0.001
xI = x1
if abs(eval(eqVar, {"xI": xI})) <= 0.0001:
self.verifyRoots(roots, counters, xI, counter)
break
if counter > 1000:
break
if bigCount > 200:
if len(roots) == 0:
messagebox.showinfo(
title="T&E",
message="The number of iterations exceeded the number of iterations by T&E, could not be solved by this method.",
)
return roots
break
roots = self.cleanArray(roots, 0.1)
self.giveAnswers(
self.tanteoOutput, self.tanteoIterationsOutput, roots, counters
)
return roots
def biseccion(self):
roots = []
counters = []
bigCount = 0
eqVar, degree = self.getEntry()
while len(roots) < degree:
bigCount += 1
counter = 0
xLow, xHigh = self.rndNumbers(eqVar, roots)
while True:
counter += 1
xMiddle = (xHigh + xLow) / 2
if eval(eqVar, {"xI": xMiddle}) > 0:
xHigh = xMiddle
else:
xLow = xMiddle
if abs(eval(eqVar, {"xI": xMiddle})) <= 0.0001:
self.verifyRoots(roots, counters, xMiddle, counter)
break
if counter > 1000:
if len(roots) == 0:
messagebox.showinfo(
title="Bisection",
message="The number of iterations exceeded the number of iterations by Bisection, could not be solved by this method.",
)
return roots
break
if bigCount > 200:
break
roots = self.cleanArray(roots, 0.1)
self.giveAnswers(
self.biseccionOutput, self.biseccionIterationsOutput, roots, counters
)
return roots
def biseccionGraph(self):
roots = []
counters = []
bigCount = 0
eqVar, degree = self.getEntry()
while len(roots) < degree:
bigCount += 1
counter = 0
xLow, xHigh = self.rndNumbers(eqVar, roots)
while True:
counter += 1
xMiddle = (xHigh + xLow) / 2
if eval(eqVar, {"xI": xMiddle}) > 0:
xHigh = xMiddle
else:
xLow = xMiddle
if abs(eval(eqVar, {"xI": xMiddle})) <= 0.0001:
self.verifyRoots(roots, counters, xMiddle, counter)
break
if counter > 10000:
if len(roots) == 0:
messagebox.showinfo(
title="Bisection",
message="The number of iterations exceeded the number of iterations by Bisection, could not be solved by this method.",
)
return roots
break
if bigCount > 500:
break
roots = self.cleanArray(roots, 0.1)
return roots
def reglaFalsa(self):
roots = []
counters = []
bigCount = 0
eqVar, degree = self.getEntry()
while len(roots) < degree:
bigCount += 1
counter = 0
xLow, xHigh = self.rndNumbers(eqVar, roots)
while True:
counter += 1
if eval(eqVar, {"xI": xLow}) == 0:
self.verifyRoots(roots, counters, xLow, counter)
break
if eval(eqVar, {"xI": xHigh}) == 0:
self.verifyRoots(roots, counters, xHigh, counter)
break
if xHigh - xLow == 0:
self.verifyRoots(roots, counters, xHigh, counter)
break
xMiddle = xLow - (eval(eqVar, {"xI": xLow})) * (xHigh - xLow) / (
eval(eqVar, {"xI": xHigh}) - eval(eqVar, {"xI": xLow})
)
if eval(eqVar, {"xI": xMiddle}) > 0:
xHigh = xMiddle
else:
xLow = xMiddle
if abs(eval(eqVar, {"xI": xMiddle})) <= 0.0001:
self.verifyRoots(roots, counters, xMiddle, counter)
break
if counter > 1000:
break
if bigCount > 200:
if len(roots) == 0:
messagebox.showinfo(
title="Regula Falsi",
message="The number of iterations exceeded the number of iterations by Regula Falsi, could not be solved by this method.",
)
return roots
break
roots = self.cleanArray(roots, 0.1)
self.giveAnswers(
self.reglaFalsaOutput, self.reglaFalsaIterationsOutput, roots, counters
)
return roots
def newtonRaphson(self):
try:
roots = []
counters = []
bigCount = 0
eqVar, degree = self.getEntry()
eqDerivative = self.getDerivative()
while len(roots) < degree:
bigCount += 1
counter = 0
x0 = self.getIntSeed(roots)
while True:
counter += 1
if (eval(eqVar, {"xI": x0})) == 0:
self.verifyRoots(roots, counters, x0, counter)
break
if (eval(eqDerivative, {"xI": x0})) == 0:
self.verifyRoots(roots, counters, x1, counter)
break
x1 = x0 - (
(eval(eqVar, {"xI": x0})) / (eval(eqDerivative, {"xI": x0}))
)
if (eval(eqVar, {"xI": x0})) == 0:
self.verifyRoots(roots, counters, x1, counter)
break
else:
x0 = x1
if counter > 1000:
if len(roots) == 0:
messagebox.showinfo(
title="Newton Raphson",
message="The number of iterations exceeded the number of iterations by Newton Raphson, could not be solved by this method.",
)
return roots
break
if bigCount > 200:
break
roots = self.cleanArray(roots, 0.1)
self.giveAnswers(self.nROutput, self.nRIterationsOutput, roots, counters)
return roots
except:
messagebox.showinfo(
title="Newton Raphson",
message="The number of iterations exceeded the number of iterations by Newton Raphson, could not be solved by this method.",
)
return roots
def secante(self):
roots = []
counters = []
bigCount = 0
eqVar, degree = self.getEntry()
while len(roots) < degree:
bigCount += 1
counter = 0
xLow, xHigh = self.rndNumbers(eqVar, roots)
while True:
counter += 1
if (eval(eqVar, {"xI": xLow}) - eval(eqVar, {"xI": xHigh})) == 0:
break
xC = xLow - (
(eval(eqVar, {"xI": xLow}) * (xLow - xHigh))
/ (eval(eqVar, {"xI": xLow}) - eval(eqVar, {"xI": xHigh}))
)
if abs(eval(eqVar, {"xI": xC})) <= 0.0001:
self.verifyRoots(roots, counters, xC, counter)
break
elif eval(eqVar, {"xI": xLow}) * eval(eqVar, {"xI": xC}) < 0:
xHigh = xC
xC = xLow - (
(eval(eqVar, {"xI": xLow}) * (xLow - xHigh))
/ (eval(eqVar, {"xI": xLow}) - eval(eqVar, {"xI": xHigh}))
)
else:
xLow = xC
xC = xLow - (
(eval(eqVar, {"xI": xLow}) * (xLow - xHigh))
/ (eval(eqVar, {"xI": xLow}) - eval(eqVar, {"xI": xHigh}))
)
if counter > 1000:
break
if bigCount > 200:
if len(roots) == 0:
messagebox.showinfo(
title="Secant",
message="The number of iterations exceeded the number of iterations by Secant, could not be solved by this method.",
)
return roots
break
roots = self.cleanArray(roots, 0.1)
self.giveAnswers(
self.secanteOutput, self.secanteIterationsOutput, roots, counters
)
return roots
def steffensen(self):
counters = []
roots = []
eQ, degree = self.getEntry()
bigCount = 0
while len(roots) < degree:
bigCount += 1
count = 0
x0 = self.getUniformSeed(roots)
while True:
count += 1
if abs(eval(eQ, {"xI": x0})) <= 0.0001:
self.verifyRoots(roots, counters, x0, count)
break
else:
eqX0PlusEqX0 = eQ.replace("xI", str(x0 + eval(eQ, {"xI": x0})))
x1 = x0 - (
(eval(eQ, {"xI": x0}) ** 2)
/ (eval(eqX0PlusEqX0) - eval(eQ, {"xI": x0}))
)
if abs(eval(eQ, {"xI": x1})) <= 0.0001:
self.verifyRoots(roots, counters, x1, count)
break
else:
x0 = x1
if count > 1000:
break
if bigCount > 200:
if len(roots) == 0:
messagebox.showinfo(
title="Steffensen",
message="The number of iterations exceeded the number of iterations by Steffensen, could not be solved by this method.",
)
return roots
break
roots = self.cleanArray(roots, 0.1)
self.giveAnswers(
self.steffensenOutput, self.steffensenIterationsOutput, roots, counters
)
return roots
# Function make the graphic based on the function
def getGraphic(self, eqVar):
def restart():
self.ax.clear()
self.ax.set_xlim(-20, 20)
self.ax.set_ylim(-20, 20)
self.ax.axhline(0, color="black", linewidth="1.5")
self.ax.axvline(0, color="black", linewidth="1.5")
self.canvas.draw()
def getRedPoints():
points = self.biseccionGraph()
if len(points) != 0:
for point in points:
self.ax.scatter(point, 0, color="red", zorder=10)
# Graph function
def f(x):
return eval(eqVar, {"xI": x})
# Restart the graph to its initial state
restart()
# Defining the range for x
x = range(-1000, 1000)
# List comprehension fro the range of y
y = [f(i) for i in x]
# Drawing the plot
self.ax.plot(x, y)
# Draw red points
getRedPoints()
# Showing plot and updating canvas
plt.show()
self.canvas.draw()
# Function to make a report of everything displayed on the screen
def getReport(self):
def writePDF(methodOutput, iteracionesOutput, methodTitle, adjust):
x = 72
y = 710
doc.setFont("Courier", 12)
if methodOutput.get() != "":
doc.drawString(x, y - adjust, f"{methodTitle}: " + methodOutput.get())
doc.drawString(
x,
y - (adjust + 20),
f"{methodTitle} Iterations: " + iteracionesOutput.get(),
)
else:
doc.drawString(x, y - adjust, f"{methodTitle}: ")
doc.drawString(x, y - (adjust + 20), f"{methodTitle} Iterations: ")
try:
if not os.path.exists("Reports"):
os.makedirs("Reports")
# Verify if file exits
filepath = os.path.join("Reports", "EquationSolverReport.pdf")
i = 1
while os.path.exists(filepath):
filename = f"EquationSolverReport_{i}.pdf"
filepath = os.path.join("Reports", filename)
i += 1
# Create PDF doc
doc = canvas.Canvas(filepath, pagesize=A4)
now = datetime.datetime.now()
date_string = now.strftime("%d/%m/%Y %H:%M:%S")
doc.setFont("Courier", 12)
doc.drawString(14 * mm, 280 * mm, date_string)
# Write title
doc.setFont("Courier-Bold", 18)
doc.drawString(20 * mm, 265 * mm, "Report: Equation Solver")
doc.setFont("Courier-Bold", 12)
doc.drawString(72, 715, self.eqEntry.get())
doc.setFont("Courier", 12)
writePDF(self.tanteoOutput, self.tanteoIterationsOutput, "T&E", 20)
writePDF(
self.biseccionOutput, self.biseccionIterationsOutput, "Bisection", 70
)
writePDF(
self.reglaFalsaOutput,
self.reglaFalsaIterationsOutput,
"Regula Falsi",
120,
)
writePDF(self.nROutput, self.nRIterationsOutput, "Newton Raphson", 170)
writePDF(self.secanteOutput, self.secanteIterationsOutput, "Secant", 220)
writePDF(
self.steffensenOutput,
self.steffensenIterationsOutput,
"Steffensen",
270,
)
imageName = "temp_graph.png"
filepathImg = os.path.join(os.getcwd(), imageName)
# Save figure
self.canvas.print_figure(filepathImg, bbox_inches="tight")
with open("temp_graph.png", "rb") as f:
img = ImageReader(f)
doc.drawImage(img, 180, 70, width=242, height=310)
os.remove("temp_graph.png")
# Save and close PDF
doc.save()
messagebox.showinfo(
"Generated report", f"The report is generated in: {filepath}"
)
except:
messagebox.showerror(
"Error PDF", "An error occurred while trying to save the file."
)
# Python entry Point
if __name__ == "__main__":
# Shortcut name to call tkinter
root = tk.Tk()
# App name
root.title("Equation Solver")
# Making resizable or not
root.resizable(True, True)
# Graph style
style.use("fivethirtyeight")
# App theme
root.tk.call("source", "./src/Tk Theme/azure.tcl")
root.tk.call("set_theme", "dark")
# App icon
root.iconbitmap("./public/images/sine.ico")
# Instancing object
app = App(root)
app.pack(fill="both", expand=True)
# Always appear on screen center
root.update()
root.minsize(root.winfo_width(), root.winfo_height())
x_cordinate = int((root.winfo_screenwidth() / 2) - (root.winfo_width() / 2))
y_cordinate = int((root.winfo_screenheight() / 2) - (root.winfo_height() / 2))
root.geometry("+{}+{}".format(x_cordinate, y_cordinate - 20))
# Main loop function
root.mainloop()