Created
July 30, 2024 19:41
-
-
Save tiye/090222636126be94d9734bf7d5679d7b to your computer and use it in GitHub Desktop.
Claude AI answer for https://codegolf.stackexchange.com/questions/249439/draw-this-fractal-generated-by-applying-newtons-method-to-coshx-1#comment556929_249500
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
use image::{ImageBuffer, Rgb}; | |
use num_complex::Complex; | |
use std::f64::consts::PI; | |
const WIDTH: u32 = 512; | |
const HEIGHT: u32 = 255; | |
const MAX_ITERATIONS: u32 = 99; | |
fn main() { | |
let mut img = ImageBuffer::new(WIDTH, HEIGHT); | |
for (x, y, pixel) in img.enumerate_pixels_mut() { | |
let mut z = Complex::new(x as f64 / 256.0 - 1.0, y as f64 / 256.0 - 0.5 + PI); | |
let result = (0..MAX_ITERATIONS).find_map(|i| { | |
z -= (z.cosh() - 1.0) / z.sinh(); | |
let attractor_distance = z.im - ((z.im / (2.0 * PI)).round() * 2.0 * PI); | |
if z.re.abs().max(attractor_distance.abs()) < 0.01 { | |
Some((z, i)) | |
} else { | |
None | |
} | |
}); | |
if let Some((z, iterations)) = result { | |
let hue = (z.im / PI / 2.0 + 36.0).rem_euclid(8.0) / 8.0; | |
let saturation = 1.0; | |
let value = 1.0 - (iterations as f64 / MAX_ITERATIONS as f64); | |
let (r, g, b) = hsv_to_rgb(hue, saturation, value); | |
*pixel = Rgb([r, g, b]); | |
} else { | |
*pixel = Rgb([0, 0, 0]); // Black for points that didn't converge | |
} | |
} | |
img.save("fractal.png").unwrap(); | |
} | |
fn hsv_to_rgb(h: f64, s: f64, v: f64) -> (u8, u8, u8) { | |
let c = v * s; | |
let x = c * (1.0 - ((h * 6.0) % 2.0 - 1.0).abs()); | |
let m = v - c; | |
let (r, g, b) = match (h * 6.0).floor() as i32 { | |
0 => (c, x, 0.0), | |
1 => (x, c, 0.0), | |
2 => (0.0, c, x), | |
3 => (0.0, x, c), | |
4 => (x, 0.0, c), | |
_ => (c, 0.0, x), | |
}; | |
( | |
((r + m) * 255.0) as u8, | |
((g + m) * 255.0) as u8, | |
((b + m) * 255.0) as u8, | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment