---
title: "CKKS encode 3"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{CKKS encode 3}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
Load libraries that will be used.
```{r setup}
library(polynom)
library(HomomorphicEncryption)
```
Set a working seed for random numbers (so that random numbers can be replicated exactly).
```{r seed}
set.seed(123)
```
Set some parameters.
```{r params}
M <- 8
N <- M / 2
scale <- 4
xi <- complex(real = cos(2 * pi / M), imaginary = sin(2 * pi / M))
```
Create the (complex) numbers we will encode.
```{r z}
z <- c(complex(real=3, imaginary=4), complex(real=2, imaginary=-1))
print(z)
```
Now we encode the vector of complex numbers to a polynomial.
```{r encode}
pi_z <- pi_inverse(z)
scaled_pi_z <- scale * pi_z
rounded_scale_pi_zi <- sigma_R_discretization(xi, M, scaled_pi_z)
p <- sigma_inverse(xi, M, rounded_scale_pi_zi)
coef <- as.vector(round(Re(p)))
p <- polynomial(coef)
```
Let's view the result.
```{r print-p}
print(p)
```
Let's decode to obtain the original number:
```{r decode}
rescaled_p <- coef(p) / scale
z <- sigma_function(xi, M, rescaled_p)
decoded_z <-pi_function(M, z)
print(decoded_z)
```
The decoded z is indeed very close to the original z, we round the result to make the clearer.
```{r round}
round(decoded_z)
```
Next, work through the CKKS-encode-2 vignette, which breaks down the encode and decode functions into the individual steps.