获得一个浮动的小数部分,而无需使用MODF() [英] Getting the fractional part of a float without using modf()

查看:177
本文介绍了获得一个浮动的小数部分,而无需使用MODF()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在开发没有数学库的平台,所以我需要建立自己的工具。我目前得到的分数的方法是将浮动转换为固定点(用(浮点)0xFFFF的,强制转换为int乘),只得到了下部(与0xFFFF MASK),并将其转换回再次上浮。

I'm developing for a platform without a math library, so I need to build my own tools. My current way of getting the fraction is to convert the float to fixed point (multiply with (float)0xFFFF, cast to int), get only the lower part (mask with 0xFFFF) and convert it back to a float again.

不过,IM precision是我的命。我用我的压裂()和InvFrac()函数来绘制一个反走样线。使用 MODF 我得到一个完美流畅的线条。用我自己的方法像素开始跳来跳去由于precision损失。

However, the imprecision is killing me. I'm using my Frac() and InvFrac() functions to draw an anti-aliased line. Using modf I get a perfectly smooth line. With my own method pixels start jumping around due to precision loss.

这是我的code:

const float fp_amount = (float)(0xFFFF);
const float fp_amount_inv = 1.f / fp_amount;

inline float Frac(float a_X)
{
    return ((int)(a_X * fp_amount) & 0xFFFF) * fp_amount_inv;
}

inline float Frac(float a_X)
{
    return (0xFFFF - (int)(a_X * fp_amount) & 0xFFFF) * fp_amount_inv;
}

在此先感谢!

推荐答案

如果我正确地理解你的问题,你只想小数点右边后的部分?你不需要它实际上在一小部分(整数分子和分母)?

If I understand your question correctly, you just want the part after the decimal right? You don't need it actually in a fraction (integer numerator and denominator)?

因此​​,我们有一些数字,说 3.14159 ,我们希望只用 0.14159 来结束。假设我们的数字存储在浮动F; ,我们可以这样做:

So we have some number, say 3.14159 and we want to end up with just 0.14159. Assuming our number is stored in float f;, we can do this:

f = f-(long)f;

其中,如果我们插入了一些,是这样的:

Which, if we insert our number, works like this:

0.14159 = 3.14159 - 3;

这样做是去除浮动只留下小数部分的整数部分。当您转换浮子长,它丢弃小数部分。然后,当你减去从原始的浮动,留给你的只有的小数部分。我们需要用很长的这里,是因为的 float类型(在大多数系统8个字节)的大小。一个整数(在许多系统上只有4个字节)未必大到足以覆盖同样范围的数字作为浮动的,但应该的。

What this does is remove the whole number portion of the float leaving only the decimal portion. When you convert the float to a long, it drops the decimal portion. Then when you subtract that from your original float, you're left with only the decimal portion. We need to use a long here because of the size of the float type (8 bytes on most systems). An integer (only 4 bytes on many systems) isn't necessarily large enough to cover the same range of numbers as a float, but a long should be.

这篇关于获得一个浮动的小数部分,而无需使用MODF()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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