Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BigQueryでNewton法 #34

Open
takegue opened this issue Aug 13, 2022 · 0 comments
Open

BigQueryでNewton法 #34

takegue opened this issue Aug 13, 2022 · 0 comments
Assignees

Comments

@takegue
Copy link
Owner

takegue commented Aug 13, 2022

BigQueryでNewton法

Newton法では次の漸化式で、Nの平方根を求めることができる:

$$ x_{n+1} = x_{n} - \frac{x^2 - N}{2 x} $$

漸化式で表されるものは、WITH RECURSIVEで表すことができる.
この実装は次のようになる。

このSQLにおいては、 2~1000までの数字の平方根を求めることができる。

with 
  recursive newton as (
	-- Initial step
    select 0 as n, 1 + 0.5 * (N - 1) as x, N as tgt from unnest(generate_array(2, 1000)) as N
    union all
	-- Update step
    select 
      n + 1
      , x - (x * x - tgt) / (2 * x)
      , tgt
    from newton
    where 
      -- Maximum recursive depth 
      n < 98
      -- tolerance error
      and abs(x * x - tgt) > 1e-06
  )

  select *, tgt - x*x as e from newton
  qualify n = max(n) over (partition by tgt) 
  order by tgt
@takegue takegue added the blog label Aug 13, 2022
@takegue takegue self-assigned this Aug 13, 2022
@takegue takegue changed the title WITH RECURISVEの動作をマスターする BigQueryでNewton法 Aug 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant