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 | #On the name of ALLAH
#Author : Fouad Teniou
#Date : 09/09/09
#version :2.6.1
"""
Class Interval is the base class for every Rectangle Method's approximation
and inherits from tuple. However four main functions are defined within
Interval, delta_X, and the three different approximation's methods, the
leftEndPoint, the rightEndPoint, and the midPoint. Though, RectangleMethod
class inherits from Interval class, and call the three approximation's
methods to approximate a curve function y = f(x) and compare those methods'
results. And I chose the midPoint method to compute my ell_en and logarithm
functions.
"""
from collections import namedtuple
class Interval(namedtuple('Interval','n,a,b')):
"""
Interval class inherits from tuple
"""
#set __slots__ to an empty tuple keep memory requirements low
__slots__ = ()
@property
def delta_X(self):
"""
Compute Delta_X the length value of each part of the
subinterval[a,b] divided into n equal parts
"""
return (self.b - self.a )/float(self.n)
@property
def leftEndPoint(self):
"""
Compute the value of Xk of each point using the
left endpoint of each subinterval
"""
# Start with an empty list
left_list = []
#attempt to create a list of Xk points using the left endpoint
try:
for k in range(1,self.n+1):
left_end_point = self.a + (k - 1)* self.delta_X
left_list.append(left_end_point)
return left_list
#Raise TypeError if input is not numerical
except TypeError:
print "\n<The entered value is not a number"
@property
def rightEndPoint(self):
"""
Compute the value of Xk of each point using the
right endpoint of each subinterval
"""
# Start with an empty list
right_list = []
#attempt to create a list of Xk points using the right endpoint
try:
for k in range(1,(self.n +1)):
right_end_point = self.a + (k * self.delta_X)
right_list.append(right_end_point)
return right_list
#Raise TypeError if input is not numerical
except TypeError:
print "\n<The entered value is not a number"
@property
def midPoint(self):
"""
Compute the value of Xk of each point using the midPoint
of each subinterval
"""
# Start with an empty list
mid_list = []
#attempt to create a list of Xk points using the midPoint
try:
for k in range(1,self.n + 1):
mid_point = self.a + ((k - 1/2.0)* self.delta_X)
mid_list.append(mid_point)
return mid_list
#Raise TypeError if input is not numerical
except TypeError:
print "\n<The entered value is not a number"
class RectangleMethod(Interval):
"""
Class RectangleMethod inherit from Interval class
"""
def Curve(self,**args):
"""
Compute and display the Left Endpoint, the Right Endpoint
and the midPoint approximaions of the area under a curve y = f(x)
over an interval [a,b]
"""
self.args = args
count = 0 #Set count to 0
total = 0 #Set total to 0
print '\n\t\tLeft Endpoint Approximation'
print '\t\t----------------------------'
print '\nk\t\tX_k\t\ty','\n'
# the curve y = f(x) is set to the 3rd degree of a form a + X**n
# could be switched into higher degree or trigonometric functions
for self.X_k in self.leftEndPoint:
self.left_curve = "%2.6f" % (self.args.get('a')*(float(self.X_k)**3)\
+ self.args.get('b') *(float(self.X_k)**2)\
+ self.args.get('c')*(float(self.X_k))+ self.args.get('d'))
count +=1
total += float(self.left_curve)
print count,'\t\t',"%2.2f" % self.X_k,'\t\t',self.left_curve
print '\t\t\t\t--------'
print '\t\t\t\t',total
print '\t\t\t\t--------'
print 'left endpoint Approximation = %s' % (self.delta_X*total)
print
count_1 = 0 #Set count_1 to 0
total_1 = 0 #Set total_1 to 0
print '\n\t\tRight Endpoint Approximation'
print '\t\t----------------------------'
print '\nk\t\tX_k\t\ty','\n'
for self.X_k in self.rightEndPoint:
self.right_curve = "%2.6f" % (self.args.get('a')*(float(self.X_k)**3)\
+ self.args.get('b') *(float(self.X_k)**2)\
+ self.args.get('c')*(float(self.X_k))+ self.args.get('d'))
count_1 +=1
total_1 += float(self.right_curve)
print count_1,'\t\t',"%2.2f" % self.X_k,'\t\t',self.right_curve
print '\t\t\t\t--------'
print '\t\t\t\t',total_1
print '\t\t\t\t--------'
print 'right endpoint Approximation = %s' % (self.delta_X*total_1)
print
count_2 = 0 #Set count_2 to 0
total_2 = 0 #Set total_2 to 0
print '\n\t\tMidpoint Approximation'
print '\t\t----------------------'
print '\nk\t\tX_k\t\ty','\n'
for self.X_k in self.midPoint:
self.mid_curve = "%2.6f" % (self.args.get('a')*(float(self.X_k)**3)\
+ self.args.get('b') *(float(self.X_k)**2)\
+ self.args.get('c')*(float(self.X_k))+ self.args.get('d'))
count_2 +=1
total_2 += float(self.mid_curve)
print count_2,'\t\t',"%2.2f" % self.X_k,'\t\t',self.mid_curve
print '\t\t\t\t--------'
print '\t\t\t\t',total_2
print '\t\t\t\t--------'
print ' midPoint Approximation = %s' % (self.delta_X*total_2)
def ell_en(self,number):
"""
Computing ellen(ln) Approximation for a given value.
"""
self.number = number
#attempt to Approximate In for a given value
try:
#Set RectangleMethod n and a fields to constant values
#and b field to a variable value, the greater the value of n
# the more accurate the result
rectangleMethod = RectangleMethod(n = 100000,a = 1, b=self.number)
sum_next = 0 #Set sum_next to 0
#inheriting and using midPoint function from Interval class
#to compute ln approximation.
for self.X_k in rectangleMethod.midPoint:
self.ell_en_X = 1/self.X_k
sum_next += self.ell_en_X
In = (sum_next * rectangleMethod.delta_X )
yield In
#Raise TypeError if input is not numerical
except TypeError:
print "\n<The entered value is not a number"
def logarithm(self,base,value):
"""
Computing logarithm approximation for a given value
and a base of choice
"""
self.base = base
self.value = value
#attempt to Approximate logarithm for a given base and value
try:
for i in self.ell_en(self.value):
pass
for j in self.ell_en(self.base):
pass
result = round(i/j,8)
return "log_b%s(%s) = : %s " % (self.base,self.value,result)
#Raise TypeError if input is not numerical
except TypeError:
print "\n<The entered value is not a number"
def exponential(self,value):
"""
Compute exponential e and exp(value) for a given value
"""
self.value = value
#attempt to yield an approximation of exp(n) for a given value
try:
for k in (1,100000000):
exp = ((1+1.0/k)**k)**value
yield exp
if self.value == 1:
print "e = %s " % repr(exp)
else:
print "exp(%s) = %s " % (value,repr(exp))
#Raise TypeError if input is not numerical
except TypeError:
print "Please enter a number "
if __name__ == '__main__':
# Create object of class RectangleMethod
rectangleMethod = RectangleMethod('n','a','b')
# create a curve y = 27 - X**2 over interval [0,3] with n =10
# for a better accuracy increase the value of n, n = 20, n = 30 ...
curve = RectangleMethod(10,0,3)
curve.Curve(a=0,b=-1,c=0,d=27)
# Create an object of ell_en to compute ln(x)
rectangleMethod = rectangleMethod._replace(b = 5)
ellen = rectangleMethod.ell_en(rectangleMethod.b)
for item in ellen:
pass
print '\n\t\tNatural Logarithm Approximation'
print '\t\t-------------------------------\n'
print "In(%s) = : %s " % (getattr(rectangleMethod,'b'),item)
# Create an object of logarithm ( base and value)
log_base_x = rectangleMethod.logarithm(2,16)
print '\n\t\tCommon Logarithm Approximation'
print '\t\t-------------------------------\n'
print log_base_x
# Create an object of exponential ( value )
print '\n\t\tExponential Approximation'
print '\t\t-------------------------\n'
for i in rectangleMethod.exponential(1):
pass
#C:\Windows\system32>python "C:\programs\Rectangle_Method.py"
# Left Endpoint Approximation
# ----------------------------
#k X_k y
#1 0.00 27.000000
#2 0.30 26.910000
#3 0.60 26.640000
#4 0.90 26.190000
#5 1.20 25.560000
#6 1.50 24.750000
#7 1.80 23.760000
#8 2.10 22.590000
#9 2.40 21.240000
#10 2.70 19.710000
# --------
# 244.35
# --------
#left endpoint Approximation = 73.305
#
#
# Right Endpoint Approximation
# ----------------------------
#
#k X_k y
#
#1 0.30 26.910000
#2 0.60 26.640000
#3 0.90 26.190000
#4 1.20 25.560000
#5 1.50 24.750000
#6 1.80 23.760000
#7 2.10 22.590000
#8 2.40 21.240000
#9 2.70 19.710000
#10 3.00 18.000000
# --------
# 235.35
# --------
#right endpoint Approximation = 70.605
#
#
# Midpoint Approximation
# ----------------------
#
#k X_k y
#
#1 0.15 26.977500
#2 0.45 26.797500
#3 0.75 26.437500
#4 1.05 25.897500
#5 1.35 25.177500
#6 1.65 24.277500
#7 1.95 23.197500
#8 2.25 21.937500
#9 2.55 20.497500
#10 2.85 18.877500
# --------
# 240.075
# --------
# midPoint Approximation = 72.0225
#
# Natural Logarithm Approximation
# -------------------------------
#
#In(5) = : 1.60943791237
#
# Common Logarithm Approximation
# -------------------------------
#
#log_b2(16) = : 4.0
#
# Exponential Approximation
# -------------------------
#
#e = 2.7182817983473577
#
#
#
|
Comments
I'd warn everybody actually interested in solving this problem that the above "recipe" should not be taken seriously.
NumPy contains many suitable integration methods. For a pure Python answer, see:
http://code.activestate.com/recipes/52292/
Rectangle Method is a chapter in CALCULUS ( Higher Mathematics Education ), and I hope that you do not warn others not to use CALCULUS.
NumPy is for beginners and not for advanced mathematics, however, you do have the choice not to use my program Rectangle_ Method, and there is no obligation!!!.
Don't you want to set up a blog? I think it would be a much better place to post your progress in calculus. Not every elementary exercise is worth a recipe. In particular, numerical integration using this rectangle method is not a good idea; e.g. Simpson's rule provides additional accuracy with the same computational effort. For "well-behaved" functions, the referenced recipe in my first comment is a good candidate, but there are many other alternatives (all of them better than this rectangle approximation).
I won't comment your strawman. Regarding NumPy, it's used for doing real computations by real professionals (although beginners can use it too).
This program is OK as an exercise for you -- but worthless for other people. The chosen integration method isn't a good one, the Python code isn't well designed at all (RectangleMethod inherits from Interval???), and isn't flexible (one cannot pass an arbitrary function, just a polynomial, and why on earth would someone want to use this program with a polinomial function?).
If you want to improve your Python skills, a good way would be to ask for comments/critics in the Python users list (python-list@python.org mirrored as the comp.lang.python newsgroup).
I think you should make this kind of comments somewhere else, as you already made a hint of setting up a blog, thus, I think I made it clear to tell you that there is no obligation!!!.
In this site people try to suggest other solutions by re-writing part of the code in a different way and discussing it with the Author, if they like the program, other wise they would spend their time doing something else rather than wasting it, by writing essays as you did to put people off writing python code, and deviate other humans from an important CHAPTER in CALCULUS,
I think that the Rectangle method integration is the best, and it is the base for the simpson’s rule and other methods, and Approximating an area under a curve is just one of a list of other mathematics’ functions where you can apply the Rectangle_method, and it is impossible for me to define a function for every possible function.
I won't comment anymore your recipes except when it's necesary to warn people against misguided info.
You think wrong. The Rectangle method with midpoint approximation has an
O(h**3)error, and Simpson isO(h**5)(h being what you called delta_X). And there are better methods.You don't have to. Just take the function as an argument.
I think you should know that the people writing Python code do not need you to warn them, since they are not stupid as you do think!!!. And they can judge for themselves what programs are suitable or not for their careers, and I hope that you do have a better thing to do with your time!!!.
I write Python programs to help students and other professionals in Mathematics and Finance fields, and my programs are fully working as you can see from the testing outcome at the bottom of each program. However, my programs’ users are not usually Python programmers and the most important thing for them is to run the program and get results, which is true while using my program ( ln and logarithm with different base ).
And the Rectangle method is the best method of Approximation, and by increasing the value of n, you will achieve better and more precise results than the scientific calculator.
There are different types of functions, such as trigonometry’s functions which are different and will need different Python functions’ definitions, thus, it is impossible to define them in the same way.
And again you used the word ( misleading ), which I think describe you better, since you are trying to put Humans off from one of the best integration’s method and while communicating indirectly to your type doing so in purpose to fool Humans, yet we still different on **birth.
That's simply not true. Even with N>1000 the Rectangle method gives far worse precision than others with, say, just 16 points. This is a known fact, one can prove it doing an error analysis (I've already posted the relevant results), and you can't really argue against it. For very large values of N, rounding and representation errors come into play so you cannot keep increasing N at will. Since there are other equally simple integration methods that give much better results, blindly using the rectangle method is just silly.
A short example showing convergence. Complete code can be found here
(BTW, see how easily I pass an arbitrary function
f1). Note that with N as low as 2, simpson returns an exact result (that's true for any polynomial of degree 3 or less). Let't try with f(x) = sin(x) in the [0,1] interval (expected value: 1-cos(1) = 0.45969769413186023)So, in this case Simpson's method with 10 points gives us the same precision as Rectangle with 300 points. (Still thinking the Rectangle method is the best?). There is a short comparison here and in the link above.
Don't misinterpret me, I don't want to imply that Simpson is the best method ever. Just that, with the same computing effort as the Rectangle method, it gives much better results. There are many other alternatives not considered here.
I noticed that you made an effort, behaved as an ordinary commentator, and tried to suggest different solutions.
However, by increasing the value of n ( n > 1000000),you will be able to achieve a better result's precision than a scientific calculator, but you might encounter a timing problem which will depend on your computer’s performance and speed.
And you could always tackle the problem of increasing the value of n, by applying some mathematics theorems. I hope that you will appreciate that the Rectangle method is a simpler method than the simpson’s rule, and this is a very important issue in the mathematics world.
I also realised that you used the Python math module to presume your functions’ suggestions, and this is the reason I developed my Rectangle_Method program, and not to use the Python math module.
Nevertheless, you are free to use whatever suit you the best, and I will carryon using the Rectangle method.
Mr Fouad Teniou link :
Profile
Career
Photos
Pi Quotation
Beyond Space Projects
https://buzzword.acrobat.com/#d=aEjxtq78QkGKUxa*UprkZQ
Sign in to comment