Question about writing out a trapezoidal integration method
Hi I am currently writing a Python program that divide 1
to 0
to n
pieces, and integrate it base on number of pieces, each trapezoid will have (10)/n
as their equal width.
Here is the code:
from numpy import sqrt,sin,arange
def f(x):
return (sin(sqrt(100*x))**2)
def trapezoidal(f, a, b, n):
h = float(b  a) / n
s = 0.0
s += f(a)/2.0
for i in range(1, n):
s += f(a + i*h)
s += f(b)/2.0
return s * h
print(trapezoidal(f(x), 5, 10, 100))
Do you guys think this code could work ?Also, how do you add a sequence or a loop that it calculate area for 1,2,4,8,16
until 2^10
?
1 answer

incorrect indentation. try this
import numpy as np def f(x): return (np.sin(np.sqrt(100*x))**2) def trapezoidal(f, a, b, n): h = float(b  a) / n s = 0.0 s += f(a)/2.0 for i in range(1, n): s += f(a + i*h) s += f(b)/2.0 return s * h print( trapezoidal(f(x), 5, 10, 100))
See also questions close to this topic

Calculate Edit Distance between two strings in Python
I want to compute the edit distance matrix between two strings, at the character level.
Here is my function:
def editDistance(r, h): ''' This function is to calculate the edit distance of reference sentence and the hypothesis sentence. Main algorithm used is dynamic programming. Attributes: r > the list of words produced by splitting reference sentence. h > the list of words produced by splitting hypothesis sentence. ''' d = numpy.zeros((len(r)+1)*(len(h)+1), dtype=numpy.uint8).reshape((len(r)+1, len(h)+1)) for i in range(len(r)+1): for j in range(len(h)+1): if i == 0: d[0][j] = j elif j == 0: d[i][0] = i for i in range(1, len(r)+1): for j in range(1, len(h)+1): if r[i1] == h[j1]: d[i][j] = d[i1][j1] else: substitute = d[i1][j1] + 1 insert = d[i][j1] + 1 delete = d[i1][j] + 1 d[i][j] = min(substitute, insert, delete) return d
Here are the inputs:
r = 'most musical instruments stores will carry in a ray of support items for guitars and other instruments such as controls in knobs items to lock your strap on your guitar a wider ray of strings in either nylon steel bronze for electric and connecting and mounting things for mounting strings in pro winders\n'
h = 'most musical instrument stores will carry an array of support items for guitars and other instruments such as controls and knobs items to lock your strap on your guitar a wide array of strings in either nylon steel bronze for electric and acoustic and classical guitars tuning machines if something goes wrong with the tuning mechanism pitch pipes hangers to hang your guitar on the wall so it s not easily knocked over and damaged connecting and mounting things for mounting strings and pro winders\n'
The function does not return anything for these inputs i.e. gets stuck infinitely.
How to fix the issue?

after installing pywin32 and pypiwin32, there are still the ImportError: No module named win32api
I tried to type scrapy crawl, after installing pywin32 and pypiwin32. It is useless. there are error of importError: No module named win32api. How to solve this?
tried to install different version for pywin32
mod = import_module(module) File "C:\Python27\Lib\importlib__init__.py", line 37, in import_module import(name) File "C:\Users\wuxin\PycharmProjects\untitled1\venv\Lib\sitepackages\scrapy\downloadermiddlewar es\retry.py", line 20, in from twisted.web.client import ResponseFailed File "C:\Users\wuxin\PycharmProjects\untitled1\venv\Lib\sitepackages\twisted\web\client.py", li ne 41, in from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS File "C:\Users\wuxin\PycharmProjects\untitled1\venv\Lib\sitepackages\twisted\internet\endpoints .py", line 41, in from twisted.internet.stdio import StandardIO, PipeAddress File "C:\Users\wuxin\PycharmProjects\untitled1\venv\Lib\sitepackages\twisted\internet\stdio.py" , line 30, in from twisted.internet import _win32stdio File "C:\Users\wuxin\PycharmProjects\untitled1\venv\Lib\sitepackages\twisted\internet_win32stdio.py", line 9, in import win32api ImportError: No module named win32api
scrapy crawl can be ranenter image description here

Predicting the next poacher attack
Is anyone able to help me with the below:
I am trying use a max_min_scaler on this data, so I can run a neural network prediction on the next poaching location
import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder import random from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.cross_validation import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score from sklearn import tree import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv('Documents/Poaching_Final.csv') df id_report date_report description longitude latitude 0 3 1/1/2005 Poaching incident 7.049359 34.841440 1 0 1/20/2005 Poaching incident 7.650840 34.480010 2 0 1/20/2005 Poaching incident 7.843202 34.005704 3 5 1/20/2005 Poaching incident 7.745846 33.948526 4 2 1/20/2005 Poaching incident 7.876673 33.690167 5 1 1/20/2005 Poaching incident 7.466248 34.066729 6 1 1/20/2005 Poaching incident 7.946153 34.220592 7 2 1/27/2005 Poaching incident 7.925990 34.857120 dataset = df.values dataset array([[3, '1/1/2005', 'Poaching incident', 7.049359, 34.841440000000006], [0, '1/20/2005', 'Poaching incident', 7.65084, 34.48001], [0, '1/20/2005', 'Poaching incident', 7.8432018029999995, 34.00570378], ..., [3, '9/29/2015', 'White Rhino', 31.89865, 28.253253000000004], [3, '10/1/2015', 'African Savannah Elephant', 28.589312, 16.884113], [2, '3/7/2015', 'White Rhino', 30.934913, 24.301232000000002]], dtype=object) X = fullData.values[:, 3:4] Y = fullData.values[:, 0] poaching_incident = df['description'] poaching_incident_encoding = poaching_incident.factorize() poaching_incident_encoding[:10] incidnt_date = df['date_report'] incidnt_date_encoding = incidnt_date.factorize() incidnt_date_encoding[:10]
Every time I try to run the below code I get the following error
from sklearn import preprocessing min_max_scaler = preprocessing.MinMaxScaler() X_scale = min_max_scaler.fit_transform(X)  ValueError Traceback (most recent call last) <ipythoninput172350511f008c8> in <module>() 1 from sklearn import preprocessing 2 min_max_scaler = preprocessing.MinMaxScaler() > 3 X_scale = min_max_scaler.fit_transform(X) ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
after I get this to work I want to split the data into a train/test set

Can't figure out Present Value (PV) formula in Google Docs spreadsheet
I'm trying to get a Google Docs spreadsheet PV (present value) formula to work in JavaScript.
Actually I have found a JavaScript PV function that works exactly like expected here: How is present value (PV) calculated on Google Sheets?
However, there's a problem to reproduce the whole formula used in the spreadsheet.
The first parameter passed to the Google Docs PV function is:
(1+61,6%)^(1/12)1
Which in my understanding would translate to this JavaScript code:
Math.pow(1 + 0.616, (1/12)) 1
If I replace the result from this JavaScript code with that Google Docs math snippet, the results don't match.
In this specific example, the original formula gives the value 20.167,95 whilst with the replacement resulted from running the JavaScript code, it gives 20.174,86.
I can't figure out why there is this difference.
Any help with that is appreciated.
EDIT:
Playing with this parameter, I was able to get the same result as the original formula by manually setting the value to 0,04082825. The value resulting from the JavaScript code is 0.04080678096462331. Very weird IMO.

Zoom in on a point with touchpad(using scale and translate and rotate in opengl or metalkit with ObjectiveC)
I just create an app like osx preview app. I use opengl or metalkit to render image. I can make zoom with a center point (0,0) by some matrix, but I can not make zoom with point between two fingers with touchpad like preview app, because I do not know how to create my model matrix.
I just ask my problem on apple develop forum, and I find demo on github, but no one can help me.
 (void)magnifyWithEvent:(NSEvent *)event { NSPoint eventLocation = [event locationInWindow]; NSPoint center = [self.view convertPoint:eventLocation fromView:nil]; NSPoint openglCenter = CGPointMake(center.x / ([[[NSApplication sharedApplication] mainWindow] frame].size.width / 2.0)  1.0, center.y / ([[[NSApplication sharedApplication] mainWindow] frame].size.height / 2.0)  1.0); NSRect frame = [[[NSApplication sharedApplication] mainWindow] frame]; if ([event magnification] > 0) { if ([self zoomValue] <= 2.0) { [self setZoomValue:[self zoomValue] + [event magnification]]; if(self.zoomValue > 2.0) { return; } self.slider.floatValue = [self zoomValue]; self.panMatrix = GLKMatrix4Translate(GLKMatrix4Identity, self.swipX / (frame.size.width / 2.0), self.swipY / (frame.size.height / 2.0), 1); self.scaleMatrix = GLKMatrix4Scale(self.baseScaleMatrix, self.zoomValue, self.zoomValue, 1); GLKMatrix4 model = GLKMatrix4Multiply(self.panMatrix, self.scaleMatrix); [self.testView makeChangeWithMat:model]; } else { [self setZoomValue:2.0]; self.slider.floatValue = [self zoomValue]; self.panMatrix = GLKMatrix4Translate(GLKMatrix4Identity, self.swipX / (frame.size.width / 2.0), self.swipY / (frame.size.height / 2.0), 1); self.scaleMatrix = GLKMatrix4Scale(self.baseScaleMatrix, self.zoomValue, self.zoomValue, 1); GLKMatrix4 model = GLKMatrix4Multiply(self.panMatrix, self.scaleMatrix); [self.testView makeChangeWithMat:model]; } } else if ([event magnification] < 0) { if ([self zoomValue] + [event magnification] >= 1.0) { [self setZoomValue:[self zoomValue] + [event magnification]]; self.slider.floatValue = [self zoomValue]; self.panMatrix = GLKMatrix4Translate(GLKMatrix4Identity, self.swipX / (frame.size.width / 2.0), self.swipY / (frame.size.height / 2.0), 1); self.scaleMatrix = GLKMatrix4Scale(self.baseScaleMatrix, self.zoomValue, self.zoomValue, 1); GLKMatrix4 model = GLKMatrix4Multiply(self.panMatrix, self.scaleMatrix); [self.testView makeChangeWithMat:model]; } else { [self setZoomValue:1.0]; if(self.zoomValue < 1.0) { return; } self.slider.floatValue = [self zoomValue]; self.panMatrix = GLKMatrix4Translate(GLKMatrix4Identity, self.swipX / (frame.size.width / 2.0), self.swipY / (frame.size.height / 2.0), 1); self.scaleMatrix = GLKMatrix4Scale(self.baseScaleMatrix, self.zoomValue, self.zoomValue, 1); GLKMatrix4 model = GLKMatrix4Multiply(self.panMatrix, self.scaleMatrix); [self.testView makeChangeWithMat:model]; } } }

How do I make a function to draw arcs inside a matrix?
I need to make a function/method that draws arcs inside a matrix. I would use 1s as points that shape the arc and 0s as empty spots. So the function would produce something like this matrix (only I would use 1400x700 matrix in reality):
000000000000000 000100000001000 000010000010000 000000111000000 000000000000000
I need to pass the following parameters to the function:
x:
the x coordinatey:
the y coordinatew:
the widthh:
the heightstart:
the start angle, in degreesextent:
the extent, in degreesNow, I don't know the math on how to do it. Anyone could help me?