python approximate intetegrator 2.0

A guy in calc class was working on a more complicated solution to the approximate integration problem, and so I felt inspired to make a few improvements:


import sys
from math import *

def main(argv):
        try :
                if argv[0] == '-h':
                        print 'usage: <function_of_x> <lower_bound> <upper_bound> <subinterval_width>';
                else :
                        function_of_x = argv[0];
                        a = float(eval(argv[1]));
                        b = float(eval(argv[2]));
                        n = float(eval(argv[3]));
                        dx = (b-a)/n;

                        # trapezoid Rule
                        def f(x) :
                                return eval(function_of_x);
                        x = a;
                        t = 0.0;
                        while (x < b) :
                                t += f(x);
                                x += dx;
                                t += f(x);

                        ft = (dx/2)*t;
                        print ("Trapezoid Rule = " + str(round(ft, 6)));

                        # midpoint Rule
                        x = a + (dx/2);
                        m = 0.0;
                        while (x <= b) :
                                m += f(x);
                                x += dx;
                        print ("Midpoint Rule = " + str(round(dx*m, 6)));

                        # Simpsons Rule
                        x = a;

                        s = 0.0;
                        while (x < b) :
                                s += f(x);
                                x += dx;
                                s += 4.0*f(x);
                                x += dx;
                                s += f(x);

                        fs = (dx/3)*s;
                        print ("Simpson's Rule = " + str(round(fs,6)));

        except IndexError:
                print 'usage: <function_of_x> <lower_bound> <upper_bound> <subinterval_width>'

if __name__ == "__main__":

calculator fatigue

tired of tediously punching away at my calculator doing approximate integration I was inspired to whip up a little python script for computing Trapezoid rule, Midpoint rule and Simpson’s rule:

import math
from math import sqrt, log
a,b,n = 0.0,1.0,4.0;
dx = (b-a)/n;

# trapezoid rule
def f(x) :
        return 34*(math.cos(x**2));
x = a;
t = f(x);
x += dx;
while ((x + dx) <= b) :
        tt = f(x);
        t += 2*tt;
        x += dx;
tt = f(x);
t += tt;
ft = (dx/2)*t;
print ("T = " + str(round(ft, 6)));

# midpoint rule
x = a + (dx/2);
m = 0.0;
while (x <= b) :
        mm = f(x);
        m += mm;
        x += dx;

print ("M = " + str(round(dx*m, 6)));

# Simpsons rule
x = a;
s = f(x);
x += dx;
while ((x + 3.0*dx) <= b) :
        ss = f(x);
        s += 4.0*ss;
        x += dx;
        ss = f(x);
        s += 2.0*ss;
        x += dx;

ss = f(x);
s += 4.0*ss;
x += dx;
ss = f(x);
s += ss;
fs = (dx/3)*s;
print ("S = " + str(round(fs,6)));

Sage Fever

Well, I should be studying Calculus, but instead I wrote another sage application for visualizing another project problem. This one is the classic cow tied to a silo problem; if the rope just reaches the far side of the silo, how much area can the cow cover?

My python is still pretty rusty, but I think I did a little better on this one than the last:

# an application for plotting "the cow tied to a silo" problem.
# author: bnr
# date: 2012-10-16
from sage.plot.line import Line
from sage.plot.arc import Arc
r,t, a1, labl1,label2 = var('r,t, a1,labl1,labl2')
# the radius of the silo
r = 1
def _( r = slider( [1..25],1, label = "Silo Radius") ): 

 #the area labels
 labl1 = text(('$ \\frac{A_1}{2} $'), (2.5*r,1.5*r),fontsize=20,color='black') 
 labl2 = text(('$A_2$'),(.5*r,1.5*r),fontsize=20,color='brown')

 # x and y on the silo perimeter 
 def x1(t): return r*cos((t))
 def y1(t): return r*sin((t))
#the area of the half-circle; A_1
 f = sqrt( (pi*r)^2 - (x -r)^2 ) 
 L1 = plot(f, r, r*(pi+1), fill=True) + labl1
# the curve of the silo wall
 L2 = parametric_plot( (x1(t), y1(t) ), (t, 0, float(pi)), color='red')

 # wrapping the rope around the silo
 def silo_rad(a):

 # finding the curve as the rope is stretched taught
 def new_x(a) : 
 new_x = x1(a) - abs( r*(pi-a)*sin(a) ) 
 return new_x

 def new_y(a) : 
 new_y = y1(a) + ( r*(pi-a)*cos(a) )
 return new_y

 # the tangent line of the taught rope
 s_tan = line( ( ( new_x(a), new_y(a) ) , ( ( x1(a),y1(a) ) ) ) )

 # the arc walked by the cow with the rope taught 
 cow = parametric_plot( (new_x(t), new_y(t) ), (t, 0, float(pi)), color='brown')
 return s_tan + cow + labl2

 # calculating the area in the half-circle
 def A1(a) : 
 return round( (pi^3)*(a^2)/2, 4)
# calculating twice the area of the integral part; A_2
 def A2(a) : 
 return round( (pi^3)*(a^2)/3, 4)
# point of tangent to silo
 def f(a):
 p1 = point( ( x1(a), y1(a) ) )
 return L1 + L2 + p1 + silo_rad(a)
# printing the calculated areas 
 print( html('$A_1= \\frac{\pi^3 r^2}{2} {\\approx} $' + str(A1(r) ) + '$\hspace{12 mm}2 \\times A_2 = \\frac{\pi^3 r^2}{3} {\\approx} $' + str(A2(r)) + '$\hspace{12 mm}Total\ Area = \\frac{5\pi^3 r^2}{6} {\\approx} $' + str(A2(r) + A1(r)) ) )

 # animating the tangent line/integral part; A_2
 a1 = animate([f(i) for i in srange(0,float(pi),.1)] , xmin = float(-2*r), xmax = float((1.1+pi)*r), ymin = float(-.2), ymax = float(1.1*pi*r))
a1.gif(savefile='my_animation.gif', show_path=False )


I haven’t posted here in a while mostly because I have been preoccupied with calculus 2; between it and my other classes I don’t have a lot of time to code. However I found an intersection between calculus and coding with one of my assignments. Charged with determining if a ball could be caught by a person riding a ferris wheel, I decided to write a Sage Notebook application that animates the two trajectories with relation to time. The result is a little rough (as is my python), but it does work.

# set the global variable
a2,t,L1,L2,min_d= var('a2,t,L1,L2,min_d')

# default high minimum distance
min_d = 1000

# these fuctions return the x's and y's
def x1(t): return 10*t
def y1(t): return 10*sqrt(3)*t-4.9*(t^2)

def x2(t): return 25+7*cos((6+t)*(-pi/6))
def y2(t): return 7+7*sin((6+t)*(-pi/6))

# two lines from the functions
L1 = parametric_plot( (x1(t), y1(t) ), (t, 0, 6), color='green')

#L2 = parametric_plot( (x2(t), y2(t) ), (t, 0, 12))
L2 = circle( (25,7),7 )

# Calclulate the distance between the points
def distance(a):
d = float( sqrt( ( x2(a)-x1(a) )^2 + (y2(a)-y1(a))^2 ) )
return d

# record minimum distance
def min_distance(distance) :
global min_d
if (distance < min_d) :
min_d = distance

# find the points at 't' on the two lines
def f(a):
p1 = point( ( x1(a), y1(a) ) )
p2 = point( ( x2(a), y2(a) ) )

#calculate distance
d = distance(a)

# record minimum distance

return L1 + L2 + p1 + p2 + text("Distance: "+ str(distance(a)),(30,16)) + text("Min Distance: "+ str(min_d),(6,16))

# the animation
a2 = animate([f(i) for i in srange(2.1,6,0.1)], xmin = 0, xmax = 35, ymin = 0, ymax = 16)

# the slider and animation checkbox
def _(Time=(0,6), animate_it = checkbox(False, "Animate it")):

if (animate_it == True) :,1)
else :
show(L1 + L2 + point( (x1(Time), y1(Time)) )+ point( (x2(Time), y2(Time)),xmin = 0, xmax = 35, ymin = 0, ymax = 16 )+ text("Distance: " + str(distance(Time)),(30,16)))

parametric trajectories
parametric trajectories with respect to time

you can see the application in action here

fedora 16

This weekend I made the switch from from Ubuntu 11.04 to Fedora 16 beta. After the last upgrade, Ubuntu started acting funny, everything from shutdown/reboot issues to glitchy UI with the new Unity desktop. I did like some of what Unity was doing, but I think it still needs a lot of work  before it is really ready; both in terms of the interface design and stability. Much of Ubuntu, like most distributions is the culmination of the efforts of the entire OS community, but the stuff that they layer on top they have to maintain themselves and I think Unity was such a big project that its release came at the cost of some of the normal “house keeping” tasks of running a linux distribution, and this may have caused some of the issues I and others have complained about (or it could simply be that to much had changed to smoothly upgrade from 10.10). I had been leaning towards giving the 11.10 release a chance to correct some of the shortcoming of the previous one but since I am taking a college course that emphasizes rpm distros, I thought it wouldn’t be a bad idea to give Fedora another go, besides, the brief look I gave gnome3 left me wanting more.

The computer I am using is  an Asus 1215t, with no optical drive and a 12″ screen  it is what some have termed “notbooks”, as in bigger than a netbook, but not really a full sized notebook. This model has the AMD neo low power cpu, integrated ATI graphic, typicall intel HD audio, and most notable a dreaded Broadcom 4313 wireless b/g/n. I think it bears mentioning that I have had little trouble with broadcom wireless in the past, though this may have just been luck. With Ubuntu wireless wouldn’t work until you otherwise connect to the internet and use the Proprietary drivers applet to install the correct driver.

Initially I installed Fedora 15, not wanting to use the beta, and also not wanting to wait the few weeks until it is finalized and  shipped, but I was not able to get the wireless card to work no matter what I tried. For this wireless card there are several drivers available: the old b43 driver that needs proprietary firmware (typically this is what Ubuntu uses), the newer broadcom-sta (aka wl) driver from Broadcom, the fallback ndiswrapper wich just wraps around an appropriate windows driver, and a newcomer the brcm80211 which is open source but still very much in the experimental stage. I tried everything, even compiling the wl driver from the source provide from Broadcom even though there are binaries in the Fedora repos. I never did get the brcm80211 driver to compile, but considering the shape it is currently in that is not a big surprise. It is likely that ndiswrapper would have worked had I not been using a 64bit distro, and the only available drivers are 32bit. I had just about given up hope when I decided to try the beta before running back to Ubuntu. The Fedora 16 beta didn’t have the wbroadcom-sta driver in the repositories, only the b43, which didn’t work. However, after installing the kernel-devel package I was able to compile the source provide by broadcom and it works perfectly.

I have only had a few days with the new gnome3 desktop, but so far I like it, even more than Unity. It is a little different, and takes getting used to but I think in the end it is an improvement over the old classic gnome interface. Some have complained that nothing in the GnomeShell (the default graphical environment that ships with gnome3) can be customized like in classic gnome, but gnome3 is just the framework, in time no doubt people will write their own graphic shells that use gnome3, or applications that allow the tweaking of elements within an installed shell. Since most of the shell is written in JavaScript (with a couple additional libraries) anyone with a little programming knowledge should be able to play with the interface, or write their own.

found findbugs

I recently found findbugs, a static analysis tool for Java. I ran it on mdb2mysql and was surprised to only find one “serious” bug, a possible null pointer deference. I think it was actually a false positive since the value in question was checked against being null, but switching the code block to a try catch is the more stylistically correct way to handle it. Other than that there were a few performance issues with the way I put the sql statements together; I should have known better than to just concatenate strings without using StringBuffer explicitly. The beauty of static analysis is that findbugs can scan the code and find these little things as the code is being developed and remind me to tie up loose ends and sort out dirty code. I can see that using it and other tools should help me become a better programer.

However, most of the issues I need to tackle are not ones that static analysis will uncover: inelegant code, method misuse, unnecessary variables. A lot of these things are technically correct in that they work and can’t throw any errors, but that doesn’t mean they are easy to understand and maintain or that they are the most efficient way  to achieve the goal of the program.

And of course  that ignores the all issues of UI design. Currently both the CLI and GUI of mdb2mysql need lots of work; the program is functional, but the GUI is missing many “GUI” features such as tab focus switching, execute/next input  with ‘enter’ from text input, additionally I would like to eliminate the modal dialogs. The CLI also is extremely clunky; there are branches that trap the user into irreversible action were the only options are to move forward or kill the application.