Welcome, guest | Sign In | My Account | Store | Cart

My program Rectangle_Method could be used for finding areas of an interval [a,b] under a curve y = f(x) by dividing the interval [a,b] into n equal subintervals and constructing a rectangle for each subinterval. However, the greater the number of subintervals (n) the better is the approximation of the area, though, we should choose an X_k value to find the height of a rectangle in each subinterval, thus, assessing the curve y = f(x). The left endpoint, the right endpoint or the midpoint approximations of each subinterval could be used to compute the area under the curve y = f(x). The rectangle method ( midpoint approximation ) could be used to approximate mathematics' functions, such as integrals, ln, log, trigonometric functions ( sin, cos, tan, cot ), the value of Pi and other functions with accuracy, the higher the value of (n) the more accurate the result, and my mathematics' program Rectangle Method could be used for this purpose.

Python, 610 lines
  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
#On the name of ALLAH and may the blessing and peace of Allah 
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#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
#    
#        
#  
    
##########################################################################################
# Version : Python 3.2
#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 n value the
#            # the more accurate 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 ")
#

Mr Fouad Teniou new link:

1-Profile

2-Career

3-Photos

4-Pi Quotation

5-Beyond Space Project

6-Door's shape Design (photoshop art work) and quotation

https://acrobat.com/#d=aEjxtq78QkGKUxa*UprkZQ

13 comments

Gabriel Genellina 12 years, 3 months ago  # | flag

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/

Fouad Teniou (author) 12 years, 3 months ago  # | flag

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!!!.

Gabriel Genellina 12 years, 2 months ago  # | flag

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).

Fouad Teniou (author) 12 years, 2 months ago  # | flag

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.

Gabriel Genellina 12 years, 2 months ago  # | flag

I think you should make this kind of comments somewhere else

I won't comment anymore your recipes except when it's necesary to warn people against misguided info.

I think that the Rectangle method integration is the best, and it is the base for the simpson’s rule and other methods,

You think wrong. The Rectangle method with midpoint approximation has an O(h**3) error, and Simpson is O(h**5) (h being what you called delta_X). And there are better methods.

it is impossible for me to define a function for every possible function.

You don't have to. Just take the function as an argument.

Fouad Teniou (author) 12 years, 2 months ago  # | flag

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.

Gabriel Genellina 12 years, 2 months ago  # | flag

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.

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

# equivalent to your midPoint, I presume
def rectangle_m(f, a, b, N=100):
    h = float(b - a)/N
    return  h * sum(f(a + h*k + h/2.0) for k in xrange(N))

# another method, same complexity, better results
def simpson(f, a, b, N=100):
    assert not N%2, "N must be even!"
    h = float(b - a)/N
    return  h/3 * (f(a) + sum(2**(k%2 + 1) * f(a + h*k) for k in xrange(1,N)) + f(b))

# your original function
def f1(x): return 27 - x**2


>>> rectangle_m(f1, 0, 3, N=10)
72.022500000000008
>>> simpson(f1, 0, 3, N=10)
72.0
>>> simpson(f1, 0, 3, N=2)
72.0
>>> rectangle_m(f1, 0, 3, 100)
72.000224999999972
>>> rectangle_m(f1, 0, 3, 1000)
72.000002249999952
>>> rectangle_m(f1, 0, 3, 10000)
72.000000022500032
>>> rectangle_m(f1, 0, 3, 100000)
72.000000000225114
>>> rectangle_m(f1, 0, 3, 1000000)
72.000000000001904

(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)

>>> from math import sin
>>> rectangle_m(sin, 0, 1, N=10)
0.45988929071851814       # 3 significant figures
>>> simpson(sin, 0, 1, N=10)
0.45969794982382062       # 6 fig
>>> # how large N to obtain the same precision?
>>> rectangle_m(sin, 0, 1, 30)
0.45971897712223891              # 4 significant figures
>>> rectangle_m(sin, 0, 1, 100)
0.45969960954450584              # 5 fig
>>> rectangle_m(sin, 0, 1, 300)
0.45969790695493601              # 6 fig

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.

Fouad Teniou (author) 12 years, 2 months ago  # | flag

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.

Fouad Teniou (author) 12 years, 2 months ago  # | flag

Mr Fouad Teniou link :

  1. Profile

  2. Career

  3. Photos

  4. Pi Quotation

  5. Beyond Space Projects

https://buzzword.acrobat.com/#d=aEjxtq78QkGKUxa*UprkZQ

Fouad Teniou (author) 12 years ago  # | flag

Mr Fouad New link 1-Profile 2-Career 3-Photos 4-Pi Quotation 5-Beyond Space Projects 6- Fouad Design Art work

https://acrobat.com/#d=dYK7o73yUkCMHK*0wyukiw

Fouad Teniou (author) 12 years ago  # | flag

Mr Fouad Teniou new link:

1-Profile

2-Career

3-Photos

4-Pi Quotation

5-Beyond Space Project

6-Door's shape Design (photoshop art work) and quotation

https://acrobat.com/#d=aEjxtq78QkGKUxa*UprkZQ

Fernando Nieuwveldt 11 years, 12 months ago  # | flag

n > 1000000??? I think you should take Gabriel's advice. Never did I hear that the rectangle method is the best. If someone give you pointers you should think about it and do your research. As in this case a classic rounding error problem.

Take the advise people give you thats how you learn!!!

Fouad Teniou (author) 11 years, 12 months ago  # | flag

And I think that you should take the same advice I gave to Gabriel

"Nevertheless, you are free to use whatever suit you the best, and I will carryon using the Rectangle method."