How to return sum of two normalized values in a normalized output

江枫思渺然 提交于 2019-12-24 11:29:44

问题


I need a function that takes a and b both in [0..1] range, and adds a and b and returns the output in [0..1] range, when the sum is above 1 it wraps to zero like mod function.

I tried this but it doesn't work:

function shift(a, b) {
  return (a + b) % 1;
}

For example for a = 1 and b = 0, it returns 0 but I want it to return 1.


回答1:


I think the best you can do is something like:

function normalize(a, b) {
  let r = (a + b);
  return r === 1 ? 1 : r % 1;
}

This will return 0 when the sum is exactly 0, and 1 when the sum is exactly 1. Other values "wrap" back into the 0 ... 1 range.




回答2:


I see three conditions here

1) When both of them are 1, the sum will be 2, in which case you have to return 0

2) When the sum is greater than 1, but not 2, in which case subtract 1

3) When the sum is less than 1, return the sum

function f(a,b){
    s = (a+b)

    if(s == 2)
        return s-2
    else if (s > 1)
        return s-1
    else 
        return s
}

I hope this helps.



来源:https://stackoverflow.com/questions/57539049/how-to-return-sum-of-two-normalized-values-in-a-normalized-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!