Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. use std::f32::consts::PI as PI;
  2. use num::Complex;
  3.  
  4. trait OutputType {}
  5. impl OutputType for f32 {}
  6. impl OutputType for Complex<f32> {}
  7.  
  8. struct Nco<T> {
  9. phase: f32,
  10. delta_phase: f32,
  11. frequency: f32,
  12. sample_rate: f32,
  13. output_type: T,
  14. }
  15.  
  16. impl<T: OutputType> Nco<T> {
  17. pub fn new(frequency: f32, sample_rate: f32, output_type: T) -> Nco<T> {
  18. let dp = 2.0 * PI * frequency / sample_rate;
  19. Nco { phase: -dp,
  20. delta_phase: dp,
  21. frequency,
  22. sample_rate,
  23. output_type, }
  24. }
  25.  
  26. pub fn with_phase(mut self, phase: f32) -> Nco<T> {
  27. self.phase += phase;
  28. self
  29. }
  30.  
  31. fn click(&mut self) {
  32. self.phase = (self.phase + self.delta_phase) % (2.0 * PI);
  33. }
  34. }
  35.  
  36. impl Iterator for Nco<f32> {
  37. type Item = f32;
  38.  
  39. fn next(&mut self) -> Option<Self::Item> {
  40. self.click();
  41. Some(self.phase.cos())
  42. }
  43. }
  44.  
  45. impl Iterator for Nco<Complex<f32>> {
  46. type Item = Complex<f32>;
  47.  
  48. fn next(&mut self) -> Option<Self::Item> {
  49. self.click();
  50. Some(Complex::from_polar(&1.0, &self.phase))
  51. }
  52. }
  53.  
  54.  
  55. fn main() {
  56.  
  57. let real = Nco::new(440.0, 32000.0, 0f32);
  58. let complex = Nco::new(440.0, 32000.0, Complex::new(0f32, 0f32));
  59.  
  60. let res = real.take(4).zip(complex.take(4))
  61. .all(|(x, z)| (x-z.re).abs() < 0.000001 );
  62.  
  63. if res {
  64. println!("Equal");
  65. } else {
  66. println!("Not equal")
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement