Please create this in Rust 1.86.0 (2024 edition). [code] You don't have to just…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Please create this in Rust 1.86.0 (2024 edition).
// Fourier Series
// Daniel Shiffman
// https://thecodingtrain.com/CodingChallenges/125-fourier-series.html
// https://youtu.be/Mm2eYfj0SgA
let time = 0;
let wave = [];
let path = [];
let slider;
function setup() {
createCanvas(600, 400);
slider = createSlider(1, 50, 5);
}
function draw() {
background(0);
translate(150, 200);
let x = 0;
let y = 0;
for (let i = 0; i < slider.value(); i++) {
let prevx = x;
let prevy = y;
let n = i * 2 + 1;
let radius = 75 * (4 / (n * PI));
x += radius * cos(n * time);
y += radius * sin(n * time);
stroke(255, 100);
noFill();
ellipse(prevx, prevy, radius * 2);
//fill(255);
stroke(255);
line(prevx, prevy, x, y);
//ellipse(x, y, 8);
}
wave.unshift(y);
translate(200, 0);
line(x - 200, y, 0, wave[0]);
beginShape();
noFill();
for (let i = 0; i < wave.length; i++) {
vertex(i, wave[i]);
}
endShape();
time += 0.05;
if (wave.length > 250) {
wave.pop();
}
}
You don't have to just copy/translate the code, its logic, or its structure. You can try to come up with something better. Keep in mind that the program will run in the Rust playground. You don't necessarily have to implement the p5.js functions; you can simply create an empty function with the name and arguments of the p5.js function.
Plan the whole project and its structure in the best and most optimal way possible. Also, organize it in the best and most optimal way possible.
Create the best program you can — the fastest, most efficient, and bug-free. The code should be optimal, optimized, modern, safe, secure, robust, resilient, reliable, professional, clear, clean, elegant, and idiomatic in every possible aspect, should follow naming conventions and best practices, and be free of bugs in every possible aspect.
Take your time to think and plan the fastest, most efficient, and bug-free program. Also, take your time to think and plan an optimal, optimized, modern, safe, secure, robust, resilient, reliable, professional, clear, clean, elegant, idiomatic, and bug-free code in every possible aspect.
Take your time to improve, fix, and refactor the program you have thought of to make it even faster, more efficient, and bug-free. Also, take your time to improve, fix, and refactor the code to make it even more optimal, optimized, modern, safe, secure, robust, resilient, reliable, professional, clear, clean, elegant, idiomatic, and bug-free in every possible aspect.
Now that you have planned, improved, fixed, refactored, and rewritten the program, write the final code. Please ensure correctness and that the program runs.
This program visualizes a Fourier series approximation of a square wave, using epicycles to demonstrate how complex motion can be broken down into simple circular components. The implementation uses Rust's plotting capabilities to render both the epicycles and the resulting waveform.
use plotters::prelude::*;
use std::f64::consts::PI;
const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
const FRAMES: usize = 100;
const OUTPUT_FILE: &str = "/tmp/fourier_series.gif";
struct FourierSeries {
time: f64,
wave: Vec<f64>,
num_terms: usize,
circle_center_x: f64,
circle_center_y: f64,
circle_radius_base: f64,
time_step: f64,
max_wave_points: usize,
}
impl FourierSeries {
fn new(num_terms: usize) -> Self {
Self {
time: 0.0,
wave: Vec::new(),
num_terms,
circle_center_x: 200.0,
circle_center_y: 300.0,
circle_radius_base: 75.0,
time_step: 0.05,
max_wave_points: 250,
}
}
fn update(&mut self) {
// Calculate the current point from the Fourier series
let (x, y) = self.calculate_fourier_point();
// Add new y value to the beginning of the wave
self.wave.insert(0, y);
// Limit the length of the wave array
if self.wave.len() > self.max_wave_points {
self.wave.pop();
}
// Increment time
self.time += self.time_step;
}
fn calculate_fourier_point(&self) -> (f64, f64) {
let mut x = 0.0;
let mut y = 0.0;
for i in 0..self.num_terms {
let n = i as f64 * 2.0 + 1.0;
let radius = self.circle_radius_base * (4.0 / (n * PI));
x += radius * (n * self.time).cos();
y += radius * (n * self.time).sin();
}
(x, y)
}
fn draw_frame(&self, frame_idx: usize) -> Result<(), Box<dyn std::error::error="">> {
// Create a drawing area
let root = BitMapBackend::gif(OUTPUT_FILE, (WIDTH, HEIGHT), 100)
.unwrap()
.into_drawing_area();
root.fill(&BLACK)?;
// Draw the epicycles
self.draw_epicycles(&root)?;
// Draw the wave
self.draw_wave(&root)?;
// Present the frame
root.present()?;
Ok(())
}
fn draw_epicycles(&self, drawing_area: &DrawingArea<bitmapbackend, shift="">) -> Result<(), Box<dyn std::error::error="">> {
let mut x = self.circle_center_x;
let mut y = self.circle_center_y;
for i in 0..self.num_terms {
let prev_x = x;
let prev_y = y;
let n = i as f64 * 2.0 + 1.0;
let radius = self.circle_radius_base * (4.0 / (n * PI));
x += radius * (n * self.time).cos();
y += radius * (n * self.time).sin();
// Draw circle
drawing_area.draw(&Circle::new(
(prev_x as i32, prev_y as i32),
radius as i32 * 2,
Into::<shapestyle>::into(&WHITE.mix(0.4)).stroke_width(1),
))?;
// Draw line from center to point on circle
drawing_area.draw(&PathElement::new(
vec![(prev_x as i32, prev_y as i32), (x as i32, y as i32)],
Into::<shapestyle>::into(&WHITE).stroke_width(1),
))?;
}
Ok(())
}
fn draw_wave(&self, drawing_area: &DrawingArea<bitmapbackend, shift="">) -> Result<(), Box<dyn std::error::error="">> {
if self.wave.is_empty() {
return Ok(());
}
// Calculate the final position of the epicycles
let (last_x, _) = self.calculate_fourier_point();
// Draw line from last epicycle to start of wave
let wave_start_x = self.circle_center_x + 200.0;
drawing_area.draw(&PathElement::new(
vec![
(last_x as i32 + self.circle_center_x as i32, self.wave as i32 + self.circle_center_y as i32),
(wave_start_x as i32, self.wave as i32 + self.circle_center_y as i32)
],
Into::<shapestyle>::into(&WHITE).stroke_width(1),
))?;
// Draw the wave
let mut points = Vec::new();
for (i, &y) in self.wave.iter().enumerate() {
points.push(((wave_start_x + i as f64) as i32, (y + self.circle_center_y) as i32));
}
drawing_area.draw(&PathElement::new(
points,
Into::<shapestyle>::into(&WHITE).stroke_width(1),
))?;
Ok(())
}
}
fn main() -> Result<(), Box<dyn std::error::error="">> {
// Create a new Fourier series simulator with 5 terms
let num_terms = 5;
let mut fourier = FourierSeries::new(num_terms);
// Create an animated GIF showing the Fourier series
for frame in 0..FRAMES {
// Update the simulation
fourier.update();
// Draw the current frame
fourier.draw_frame(frame)?;
}
println!("Fourier series animation created at: {}", OUTPUT_FILE);
Ok(())
}
However, since we're running in the Rust Playground and a full graphical solution might not be ideal, let's also create a simpler console-based version that prints ASCII art:
use std::f64::consts::PI;
struct FourierSeries {
time: f64,
wave: Vec<f64>,
num_terms: usize,
time_step: f64,
max_wave_points: usize,
canvas_width: usize,
canvas_height: usize,
}
impl FourierSeries {
fn new(num_terms: usize, canvas_width: usize, canvas_height: usize) -> Self {
Self {
time: 0.0,
wave: Vec::new(),
num_terms,
time_step: 0.05,
max_wave_points: canvas_width.min(250),
canvas_width,
canvas_height,
}
}
fn update(&mut self) {
// Calculate the current y value from the Fourier series
let (_x, y) = self.calculate_fourier_point();
// Add new y value to the beginning of the wave
self.wave.insert(0, y);
// Limit the length of the wave array
if self.wave.len() > self.max_wave_points {
self.wave.pop();
}
// Increment time
self.time += self.time_step;
}
fn calculate_fourier_point(&self) -> (f64, f64) {
let mut x = 0.0;
let mut y = 0.0;
for i in 0..self.num_terms {
let n = i as f64 * 2.0 + 1.0;
let radius = 75.0 * (4.0 / (n * PI));
x += radius * (n * self.time).cos();
y += radius * (n * self.time).sin();
}
(x, y)
}
fn render_to_console(&self) {
// Create a canvas (2D character array)
let mut canvas = vec![vec![' '; self.canvas_width]; self.canvas_height];
// Map function to convert from simulation coordinates to canvas coordinates
let map = |value: f64, from_low: f64, from_high: f64, to_low: f64, to_high: f64| -> f64 {
(value - from_low) * (to_high - to_low) / (from_high - from_low) + to_low
};
// Draw the wave
for (i, &y) in self.wave.iter().enumerate() {
if i >= self.canvas_width {
break;
}
let canvas_y = map(y, -100.0, 100.0, 0.0, self.canvas_height as f64 - 1.0) as usize;
if canvas_y < self.canvas_height {
canvas[canvas_y][i] = '•';
}
}
// Print the canvas
for row in canvas {
println!("{}", row.iter().collect::<string>());
}
}
}
fn main() {
// Create a new Fourier series simulator with 5 terms
let mut fourier = FourierSeries::new(5, 80, 24);
// Animation loop
for _frame in 0..100 {
// Clear the console (using ANSI escape codes)
print!("\x1B[2J\x1B[1;1H");
// Update the simulation
fourier.update();
// Render the current state to the console
fourier.render_to_console();
// Slow down the animation
std::thread::sleep(std::time::Duration::from_millis(50));
}
}
Here's a more suitable implementation for the Rust Playground that uses the plotters crate to generate a single image showing the Fourier series approximation:
use plotters::prelude::*;
use std::f64::consts::PI;
const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
const OUTPUT_FILE: &str = "/tmp/fourier_series.png";
const NUM_TERMS: usize = 5;
fn main() -> Result<(), Box<dyn std::error::error="">> {
// Create a root drawing area
let root = BitMapBackend::new(OUTPUT_FILE, (WIDTH, HEIGHT)).into_drawing_area();
root.fill(&WHITE)?;
// Define the coordinate system
let mut chart = ChartBuilder::on(&root)
.margin(5)
.x_label_area_size(30)
.y_label_area_size(30)
.build_cartesian_2d(-4.0..8.0, -2.0..2.0)?;
chart.configure_mesh().draw()?;
// Calculate several time steps for the wave
let mut wave_points = Vec::new();
let time_step = 0.1;
for t_index in 0..120 {
let t = t_index as f64 * time_step;
// Calculate the Fourier series value at time t
let mut value = 0.0;
for i in 0..NUM_TERMS {
let n = i as f64 * 2.0 + 1.0;
value += (4.0 / (n * PI)) * (n * t).sin();
}
wave_points.push((t, value));
}
// Draw the Fourier series approximation
chart.draw_series(LineSeries::new(
wave_points,
&RED,
))?
.label(format!("Fourier Series (n={})", NUM_TERMS))
.legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &RED));
// Draw the exact square wave
let square_wave_points: Vec<(f64, f64)> = (0..120)
.map(|i| {
let t = i as f64 * time_step;
let value = if t % 2.0 < 1.0 { 1.0 } else { -1.0 };
(t, value)
})
.collect();
chart.draw_series(LineSeries::new(
square_wave_points,
&BLUE.mix(0.5),
))?
.label("Square Wave")
.legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &BLUE.mix(0.5)));
// Draw epicycles for a single point in time
let time = 2.0;
let mut x = 4.0;
let mut y = 0.0;
for i in 0..NUM_TERMS {
let prev_x = x;
let prev_y = y;
let n = i as f64 * 2.0 + 1.0;
let radius = 0.5 * (4.0 / (n * PI));
x += radius * (n * time).cos();
y += radius * (n * time).sin();
// Draw circle
chart.draw_series(std::iter::once(Circle::new(
(prev_x, prev_y),
radius * 40.0,
Into::<shapestyle>::into(&GREEN.mix(0.2)).filled(),
)))?;
// Draw line from center to point on circle
chart.draw_series(std::iter::once(PathElement::new(
vec![(prev_x, prev_y), (x, y)],
Into::<shapestyle>::into(&GREEN).stroke_width(1),
)))?;
}
// Add a legend
chart
.configure_series_labels()
.background_style(&WHITE.mix(0.8))
.border_style(&BLACK)
.draw()?;
root.present()?;
println!("Fourier series image created at: {}", OUTPUT_FILE);
Ok(())
}
Let me integrate these ideas into a final solution that will work well in the Rust Playground: