为什么该算法应该在C ++中不产生三角形输出?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double w = 1050;
double a = 1050*3;
double speed;
for(int x = 0; x <= 1050; x+=42)
{
speed = 42*((4*a)/w*abs((fmod((x-w/2),w))-w/2)*-1+w)/w;
cout << "x: " << x << " speed: " << speed << endl;
}
}
产生:
x: 0 speed: -462
x: 42 speed: -441.84
x: 84 speed: -421.68
x: 126 speed: -401.52
x: 168 speed: -381.36
x: 210 speed: -361.2
x: 252 speed: -341.04
x: 294 speed: -320.88
x: 336 speed: -300.72
x: 378 speed: -280.56
x: 420 speed: -260.4
x: 462 speed: -240.24
x: 504 speed: -220.08
x: 546 speed: -199.92
x: 588 speed: -179.76
x: 630 speed: -159.6
x: 672 speed: -139.44
x: 714 speed: -119.28
x: 756 speed: -99.12
x: 798 speed: -78.96
x: 840 speed: -58.8
x: 882 speed: -38.64
x: 924 speed: -18.48
x: 966 speed: 1.68
x: 1008 speed: 21.84
x: 1050 speed: 42
https://rextester.com/NSI24628
正确答案是 https://docs.google.com/spreadsheets/d/1XiUgHs7QYOWqggjLup0Wsx-eo0R82xrelUTTDBlgNkE/edit?usp=sharing
为什么C ++会产生线性答案,而期望三角函数呢?
答案 0 :(得分:4)
您的公式期望fmod((x-w/2),w)
的结果在[0,w)
范围内,但事实并非如此。实际范围是(-w,w)
。如果(x-w/2)
为负,则fmod
的结果为负。
简单的解决方法是将fmod((x-w/2),w)
替换为fmod((x+w/2),w)
,以确保fmod
的第一个参数为正,而不会改变总体效果。