可以"System.Math.Cos"返回(浮点数)? [英] Can "System.Math.Cos" return a (float)?

查看:66
本文介绍了可以"System.Math.Cos"返回(浮点数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,使我感到困惑的是,没有"Math.Cos"函数会返回浮点数.双精度值是唯一可以获取的值,从而迫使您将其强制转换为浮点数. 像这样:
float val = (float)Math.Cos(someVal);

In C# it bugs me how there is no "Math.Cos" function that returns a float. A double is the only value you can get back thus forcing you to cast it to a float. Like so:
float val = (float)Math.Cos(someVal);

我需要使用浮点数,因为我在Direct3D中做一些严格使用浮点数的事情. 浮点数是32位元,因此在图形世界(按现在的状态)更为常见.

I need to use floats because i'm doing stuff in Direct3D which strictly uses floats. Floats are much more common in the graphics world(as it stands now) because they are 32bit.

我可以使用C#中的任何功能来像C ++一样处理浮点数吗?

Is there any functionality within C# I can use that would simply just process floats like C++ can do??

我不想包装任何C ++东西,因为它需要在XNA&上运行.适用于OpenGL的Linux.

I do not want to wrap any C++ stuff because this needs to run on XNA & Linux for OpenGL.

注意:如果代码没有将双精度数转换为浮点数,那就太好了.

NOTE: It would nice to have code that did not cast a double to a float.

推荐答案

如果不深入学习数学,您将无法编写自己的准确 Cos函数.这是使用扩展方法的建议:

Without going into some in-depth math, you will not be able to write your own accurate Cos function. Here is a suggestion though using extension method:

class Program
{
    static void Main(string[] args)
    {
        float cos = Math.Cos(.25d).ToFloat();

        Console.WriteLine("cos(.25d) = {0}", cos);

        Console.ReadKey();
    }
}

public static class MathExtensions
{
    public static float ToFloat(this double value)
    {
        return (float)value;
    }
}

这是使用Func<T, TResult>并创建自己的MathF静态类的另一种方式:

This is another way using Func<T, TResult> and creating your own MathF static class:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("cos(.25d) = {0}", MathF.Cos(.25d));
        Console.WriteLine("sin(.25d) = {0}", MathF.Sin(.25d));

        Console.ReadKey();
    }
}

public static class MathF
{
    public static Func<double, float> Cos = angleR => (float)Math.Cos(angleR);
    public static Func<double, float> Sin = angleR => (float)Math.Sin(angleR);
}

正如其他人指出的那样,正如zezba在他的测试代码中确认的那样,Func委托的执行速度会变慢(我不知道委托的执行速度会慢得多).最快的是直接漂浮.中间问题是MathF静态类中的简单静态方法调用.

As others have pointed out, the Func delegates will be slower as zezba confirmed in his test code (I didn't know that the delegates would be that much slower). The quickest is the direct cast to float. The middle ground would be simple static method calls in the MathF static class.

这篇关于可以"System.Math.Cos"返回(浮点数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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