Skip to content

Instantly share code, notes, and snippets.

@etra0
Last active October 16, 2017 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etra0/0c0d51be62c40e456053bd437c7a9f53 to your computer and use it in GitHub Desktop.
Save etra0/0c0d51be62c40e456053bd437c7a9f53 to your computer and use it in GitHub Desktop.
Runge's phenomenom
license: gpl-3.0
height: 800
scrolling: no
border: yes
var width = 800,
height = 800;
var x = width/2,
y = height/2;
var canvas = d3.select('.canvas')
.append("svg")
.attr('width', width)
.attr('height', height);
var xScale = d3.scaleLinear()
.domain([-1, 1])
.range([0, width]);
var yScale = d3.scaleLinear()
.domain([-1, 2])
.range([height, 0]);
var size_scale = d3.scaleLinear()
.domain([-1, 1])
.range([10, 0]);
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
get getX() {
return this.x;
}
get getY() {
return this.y;
}
}
var points = [];
function runge(x) {
return 1/(1+25*Math.pow(x,2));
}
function lagrange(x) {
let sum = 0;
for (let i = 0; i < points.length; i++) {
let poly = 1;
for (let j = 0; j < points.length; j++) {
if (j != i)
poly *= (x - points[j].getX)/(points[i].getX - points[j].getX);
}
sum += runge(points[i].getX)*poly;
}
return sum;
}
var domain = [];
for (let i = -1; i <= 1; i += 0.01)
domain.push(i);
var lineFunction = d3.line()
.x(function(d) {return xScale(d);})
.y(function(d) {return yScale(runge(d));});
var lineFunctionLagrange = d3.line()
.x(function(d) {return xScale(d);})
.y(function(d) {return yScale(lagrange(d));});
canvas.append("path")
.attr("d", lineFunction(domain))
.attr("stroke", "black")
.attr("fill", "none");
canvas.append("path")
.attr("d", lineFunctionLagrange(domain))
.attr("stroke", "red")
.attr("stroke-width", 2)
.attr("class", "lagrange")
.attr("fill", "none");
canvas.on('click', function() {
x = xScale.invert(d3.mouse(this)[0]);
y = d3.mouse(this)[1];
points.push(new Point(x, y));
canvas.append("circle")
.attr("cx", xScale(x))
.attr("cy", yScale(runge(x)))
.attr("r", 5)
.attr("stroke", "none")
.attr("fill", "black");
canvas.select(".lagrange")
.transition()
.duration(500)
.attr("d", lineFunctionLagrange(domain));
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Runge's Phenomenom</title>
</head>
<body>
<div class='canvas'></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="canvas.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment