Created
September 10, 2015 11:42
-
-
Save 2bbb/c9dd5d78eb37c71fef8e to your computer and use it in GitHub Desktop.
taylor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ofMain.h" | |
double frac_table[101]; | |
double frac(int n) { | |
double v = 1; | |
for(int i = 1; i <= n; i++) { | |
v *= i; | |
} | |
return v; | |
} | |
void init_frac_table() { | |
for(int i = 0; i < 101; i++) { | |
frac_table[i] = frac(i); | |
ofLogNotice() << i << ", " << frac_table[i]; | |
} | |
} | |
double dsin(double x, int n) { | |
n = n % 4; | |
return ((n % 2) ? cos(x) : sin(x)) * ((n / 2 % 2) ? -1 : 1); | |
} | |
double a = 0.0; | |
int n = 10; | |
double taylor_sin(double x) { | |
double v = 0.0; | |
for(int i = n; 0 <= i; i--) { | |
v += dsin(a, i) * pow(x - a, i) / frac_table[i]; | |
} | |
return v; | |
} | |
double f(double x) { | |
return sin(x) * sin(2 * x); | |
} | |
double taylor_f(double x) { | |
return taylor_sin(x) * taylor_sin(2 * x); | |
} | |
class ofApp : public ofBaseApp { | |
bool bSimple; | |
public: | |
void setup() { | |
a = 0.2; | |
n = 10; | |
init_frac_table(); | |
bSimple = true; | |
ofEnableSmoothing(); | |
} | |
void update() { | |
a = ofMap(ofGetMouseX(), 0, ofGetWidth(), -10, 10); | |
} | |
void drawFunc(double (*fun)(double)) { | |
glBegin(GL_LINE_STRIP); | |
for(int i = 0; i < 1000; i++) { | |
float x = ofMap(i, 0, 1000, -10, 10); | |
glVertex2d(ofMap(i, 0, 1000, 0, ofGetWidth()), ofMap(fun(x), -1, 1, ofGetHeight() / 8, - ofGetHeight() / 8)); | |
} | |
glEnd(); | |
} | |
void draw() { | |
ofBackground(0, 0, 0); | |
for(int i = 0; i <= 100; i++) { | |
ofSetColor(255, 255, 255, i % 10 == 0 ? 127 : 64); | |
if(i == 50) ofSetColor(255); | |
ofLine(i * 0.01 * ofGetWidth(), 0, i * 0.01 * ofGetWidth(), ofGetHeight()); | |
} | |
ofSetColor(255, 0, 0); | |
ofLine(ofGetMouseX(), 0, ofGetMouseX(), ofGetHeight()); | |
ofPushMatrix(); | |
{ | |
ofTranslate(0, ofGetHeight() / 2); | |
ofSetColor(0, 0, 255); | |
if(bSimple) drawFunc(sin); | |
else drawFunc(f); | |
ofSetColor(0, 255, 0); | |
if(bSimple) drawFunc(taylor_sin); | |
else drawFunc(taylor_f); | |
} | |
ofPopMatrix(); | |
ofSetColor(255, 255, 255); | |
ofDrawBitmapString(string("n = ") + ofToString(n), 20, 20); | |
} | |
void keyPressed(int key) { | |
switch (key) { | |
case OF_KEY_UP: | |
n++; | |
if(100 < n) n = 100; | |
break; | |
case OF_KEY_DOWN: | |
n--; | |
if(n < 0) n = 0; | |
break; | |
case ' ': | |
bSimple ^= true; | |
break; | |
default: | |
break; | |
} | |
} | |
}; | |
int main() { | |
ofSetupOpenGL(1024, 512, OF_WINDOW); | |
ofRunApp(new ofApp); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment