我被要求按照这个等式找到cos:
我能够找到角度的罪,但是当找到cos时,我得到的数字与正确的值完全不同:
我使用以下代码来查找cos。 ps:我不能使用math.cos
public static double cos(double x, int n){
// declaring cos and factorial
double cos = 0.0;
// this loop determines how long does the loop go so the answer is more accurate
for (long howlong = 1 ; howlong <=n; howlong++){
double factorial =1;
// this will calculate the factorial for even numbers ex/ 2*2 = 4 , 4-2 = 2
// for the denominator
for (int factorialnumber=1; factorialnumber<=2*howlong-2; factorialnumber++){
factorial = factorial * howlong;
}
// now we need to create the pattern for the + and -
// so we use % that switches the sign everytime i increments by 1
if (howlong%2==1){
cos = cos + (double) (Math.pow(x, 2*howlong-2)/factorial);
}
else{
cos = cos - (double) (Math.pow(x, 2*howlong-2)/factorial);
}
}
return cos;
}
编辑:我弄清楚了我的错误,因为它将阶乘乘以多长而不是阶乘数。
答案 0 :(得分:1)
你有两个错误。
(错误1)你写的地方
factorial = factorial * howlong;
应该是
factorial = factorial * factorialnumber;
(错误2)您未通过外部循环重置每次迭代的因子。所以你需要移动线
double factorial =1;
向下几行,以便它在外环内。
如果您进行了这两项更改,那么cos(Math.PI / 6, 10)
的结果为0.8660254037844386
,这对我来说是正确的。
答案 1 :(得分:0)
你的阶乘的计算是错误的。 尝试使用此代码:
@IBDesignable class AttributedTextView: UITextView {
private let placeholderLabel = UILabel()
@IBInspectable var placeholder: String = "" {
didSet {
setupPlaceholderLabelIfNeeded()
textViewDidChange()
}
}
override var text: String! {
didSet {
textViewDidChange()
}
}
//MARK: - Initialization
override func awakeFromNib() {
super.awakeFromNib()
setupPlaceholderLabelIfNeeded()
NotificationCenter.default.addObserver(self, selector: #selector(textViewDidChange), name: .UITextViewTextDidChange, object: nil)
}
//MARK: - Deinitialization
deinit {
NotificationCenter.default.removeObserver(self)
}
//MARK: - Internal
func textViewDidChange() {
placeholderLabel.isHidden = !text.isEmpty
layoutIfNeeded()
}
//MARK: - Private
private func setupPlaceholderLabelIfNeeded() {
placeholderLabel.removeFromSuperview()
placeholderLabel.frame = CGRect(x: 0, y: 8, width: frame.size.width, height: 0)
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.text = placeholder
placeholderLabel.sizeToFit()
insertSubview(placeholderLabel, at: 0)
}
}
答案 2 :(得分:-1)
您的计算不正确,请转到
double value = 1;
for (int factorialnumber = 1; factorialnumber <= 2 * howlong - 2; factorialnumber++) {
value = factorialnumber * value;
}
factorial = value;
System.out.println(value + " " + (2 * howlong - 2));