Skip to content

Instantly share code, notes, and snippets.

@jasonszhao
Last active October 16, 2017 05:45
Show Gist options
  • Save jasonszhao/d365cd5dadc7f6f6657ff85df8b70a8b to your computer and use it in GitHub Desktop.
Save jasonszhao/d365cd5dadc7f6f6657ff85df8b70a8b to your computer and use it in GitHub Desktop.
Newton's Second Law Lab

Newton's Second Law Lab Code

This is for a physics paper I wrote. It just generates a model and graph. Although I am writing this for academia, the code does not count towards credit for the paper. Therefore, I release secondlaw.m and convert-units.js into the public domain. Apologies for the messy code.

To run:

octave --no-gui secondlaw.m

secondlaw2.txt is generated from the shell command ./csv-convert.js < secondlaw.txt > secondlaw2.txt.

#!/usr/bin/env node
/**
* Converts a comma and newline delimited table of [kg s] to [N m/s^2],
* assuming that deltaX = 0.500 m and v_initial = 0.
*
* Takes in input through STDIN and writes to STDOUT
*
* @author Jason Zhao <jason@codesmoothie.com>
* Date: 2017 October 12
* @license: public domain
*/
const fs=require('fs');
const input = fs.readFileSync('/dev/stdin').toString()
const print = (a) => {
console.log(typeof a + ': ' + a);
return a;
};
const result = input.split('\n').filter(l => l.match(/\S+/))
.map(line => line.split(',').map(Number))
.map(line => [line[0] * 9.8, 0.988533017 / Math.pow(line[1], 2.0) ])
.map(line => line.map(n => n.toFixed(4)).join(','))
.join('\n')
console.log(result)
Newton's Second Law Lab Code
% @author Jason Zhao <jason@codesmoothie.com>
% Date: 2017 Oct 12
% @license: public domain
1;
function theta = normal_equation(X,y)
theta = (pinv(X'*X))*X'*y
end
data = load('secondlaw3-force-vs-accel.txt');
x = data(:,1);
y = data(:,2);
% X = [x.^2, x, ones(length(x), 1)]
X = [x]
theta = normal_equation(X, y)
% function a = model(b)
% a = b * sin
% end
x_1 = 0:0.01:30;
% y_1 = eval(['@(x) ', strrep(
% strrep(
% strrep('a*x.^2 + b*x + c', 'a', num2str(theta(1))),
% 'b',
% num2str(theta(2))
% ),
% 'c',
% num2str(theta(3))
% )
% ]);
y_1 = eval(['@(x) ', strrep('a * x', 'a', num2str(theta))])
printf (func2str(y_1))
ylabel('Acceleration (m/s\^2)');
xlabel('Net Force (N)');
hold on;
axis([0 6 0 10])
plot(x, y, 'rx;Data Points;');
plot(x_1, y_1(x_1), '-;Regression;')
% plot(x, y, 'rx');
% plot(x_1, y_1(x_1), '-')
print -djpg image.jpg
pause;
0.050,1.0178
0.100,0.7343
0.150,0.6115
0.200,0.5608
0.550,0.4280
0.300,0.4713
0.400,0.4547
0.4900,0.9653
0.9800,1.8546
1.4700,2.6743
1.9600,3.1797
5.3900,5.4590
2.9400,4.5020
3.9200,4.8367
0.4900,0.6534
0.9800,1.2368
1.4700,1.8601
1.9600,2.3112
2.4500,2.9589
2.9400,3.4537
3.4300,4.0508
3.9200,4.6515
4.4100,4.7126
4.9000,5.6849
0.050,1.230
0.100,0.894
0.150,0.729
0.200,0.654
0.250,0.578
0.300,0.535
0.350,0.494
0.400,0.461
0.450,0.458
0.500,0.417
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment