研究cos(x)的一系列近似 [英] Working on a series approximation for cos(x)

查看:168
本文介绍了研究cos(x)的一系列近似的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直致力于VB项目,在给出Mclaurin系列的前N个项时,为用户提供系列近似值和cos(x)的正确值。你可能猜到VB中的cos(x)特性工作正常,我觉得代码本身很好。然而,系列近似函数不断给我一个NaN或无穷大符号。我相信可能存在我构建的功能的问题,但我不完全确定。



我尝试了什么:



代码:

I have been working on a VB project that gives the user the series approximation and correct value for cos(x) when given the first N terms of the Mclaurin series. As you can probably guess the cos(x) feature in VB works fine, and I feel as thought the code itself is fine. However, the series approx function continually gives me a NaN or an infinity symbol. I believe there could be an issue with the function I have constructed but I'm not entirely sure.

What I have tried:

The code:

Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
        Const cstPi As Single = 3.1415927
        Dim intn As Integer, inti As Integer
        Dim sngAngleDegrees As Single, sngAngleRad As Single, sngSeriesApprox As Single, sngCorrectValue As Single
        Dim sngSum As Single, sngC As Single


        sngAngleDegrees = CSng(txtAngleDegrees.Text)
        sngAngleRad = 2 * cstPi * sngAngleDegrees / 360
        intn = CInt(txtAngleRad.Text)

        sngSum = 0
        sngC = 1
        For inti = 1 To intn
            sngSum = sngSum + sngC * sngAngleRad ^ (2 * inti - 1) / LngFactorial(2 * inti - 1)
            sngC = -1 * sngC
        Next

        sngSeriesApprox = sngSum
        sngCorrectValue = Math.Cos(sngAngleRad)

        lblSA.Text = CStr(sngSeriesApprox)
        lblCV.Text = CStr(sngCorrectValue)




    End Sub





功能:



The function:

Function LngFactorial(ByVal X As Integer) As Long
        For i = X To 1 Step -1

            LngFactorial = i * LngFactorial

        Next i
        Return LngFactorial

    End Function

推荐答案

您应该学会使用调试器尽快地。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。 />
当代码不做ex的时候你已经接近了一个错误。
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.


这篇关于研究cos(x)的一系列近似的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆