MySQL php Linear Interpolation of Table

微笑、不失礼 提交于 2020-02-03 22:00:23

问题


I have a table titled "psytable_moist_air" shown below:

I'm trying to develop a MySQL statement that will interpolate a value that may be between records. (EDIT: If it is easier to do the math in PHP I'm open for that solution too!]

Example: I would like to know the "hda" value where "T" = 17.8.

Notice there is no record where "T"=17.8. However, because this table is linearly related, I can get the "hda" value where "T"=17 and the "hda" value where "T"=18 and do a linear interpolation of the values.

The result math would look like this:
(Get the "hda" value where T=17 : hda = 17.102)
(Get the "hda" value where T=18 : hda = 18.108)

EDIT: The only way I can think of is to do two MySQL statements to grab the smaller and larger values:

SELECT MAX(`T`), MAX(`hda`) FROM `psytable_moist_air` WHERE `T`<17.8
SELECT MIN(`T`), MIN(`hda`) FROM `psytable_moist_air` WHERE `T`>17.8

Then I would use these two values to do the interpolation. This works but seems pretty inefficient. Can anyone come up with a better solution??

If anyone has any advice it would be much appreciated!

.


回答1:


I believe the best way to do this would be to use the floor function.

See the following;

SET @x = 17.8;
SET @x0 = FLOOR(@x);
SET @x1 = FLOOR(@x) + 1;

SET @y0 = (SELECT `hda` FROM `psytable_moist_air` WHERE `T` = @x0);
SET @y1 = (SELECT `hda` FROM `psytable_moist_air` WHERE `T` = @x1);

SET @y = @y0 + (@y1 - @y0) * ((@x - @x0) / (@x1 - @x0));

Select @y ,@x0 ,@x1, @y0 ,@y1;



回答2:


I recently had to do this and since there is no PHP answer:

function CalcLinearInterpolation($x1, $y1, $x2, $y2, $t){
        $n = ($x2 - $x1);
        $j = ((($t - $x1) / ($n / 100)) / 100);
        $r = $y1 + ($j*($y2 - $y1));                
        return $r;
}

CalcLinearInterpolation(2, 5, 3, 9, 2.5) would return 7

To be clear;

  • 2 (x1) = 5 (y1)
  • 3 (x2) = 9 (y2)
  • 2.5 (t) = Result

So: CalcLinearInterpolation($x1, $y1, $x2, $y2, $t) in this scenario;

CalcLinearInterpolation(2, 5, 3, 9, 2.5)



来源:https://stackoverflow.com/questions/29282025/mysql-php-linear-interpolation-of-table

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