I have a knowledge base of people and how much they trust in each other based on a number, if A trusts B then B trusts A the same amount.
trusts(josemari,lucia,4.0).
trusts(raul,josemari,3.0).
trusts(luis,felipe,2.0).
trusts(manolo,felipe,2.5).
trusts(pepe,vidal,1.0).
trusts(pepe,luis,0.5).
trusts(A,B,K):-
trusts(B,A,K).
That gets me in an infinite recursion, so, how could I break the recursion? chaning the trusts predicate is not an option and rewriting the Knowledge base adding the opposits is not an option either.
If you are using SWI-Prolog, you can table the predicate. Just add a table directive:
:- table trusts/3.
trusts(josemari,lucia,4.0).
trusts(raul,josemari,3.0).
trusts(luis,felipe,2.0).
trusts(manolo,felipe,2.5).
trusts(pepe,vidal,1.0).
trusts(pepe,luis,0.5).
trusts(A,B,K):-
trusts(B,A,K).
Now it works as intended:
?- trusts(josemari, X, Y).
X = lucia,
Y = 4.0 ;
X = raul,
Y = 3.0.
?- trusts(luis, X, Y).
X = pepe,
Y = 0.5 ;
X = felipe,
Y = 2.0.
?- trusts(X, luis, Y).
X = pepe,
Y = 0.5 ;
X = felipe,
Y = 2.0.
?- trusts(A, B, K), K >= 3.0.
A = josemari,
B = lucia,
K = 4.0 ;
A = josemari,
B = raul,
K = 3.0 ;
A = lucia,
B = josemari,
K = 4.0 ;
A = raul,
B = josemari,
K = 3.0 ;
false.
If you don't have SWI-Prolog or another implementation with tabling, you need to define another rule, with a different name:
trusts(josemari,lucia,4.0).
trusts(raul,josemari,3.0).
trusts(luis,felipe,2.0).
trusts(manolo,felipe,2.5).
trusts(pepe,vidal,1.0).
trusts(pepe,luis,0.5).
trusts_commutative(A, B, K):-
trusts(A, B, K).
trusts_commutative(A, B, K):-
trusts(B, A, K).
The result is the same.
?- trusts_commutative(X, luis, Y).
X = pepe,
Y = 0.5 ;
X = felipe,
Y = 2.0.
?- trusts_commutative(A, B, K), K >= 3.0.
A = josemari,
B = lucia,
K = 4.0 ;
A = raul,
B = josemari,
K = 3.0 ;
A = lucia,
B = josemari,
K = 4.0 ;
A = josemari,
B = raul,
K = 3.0 ;
false.
You can require that A and B are bound:
trusts(A,B,K) :- nonvar(A), nonvar(B), trusts(B,A,K)
But it will work only in some cases. That is it will never get stuck but you won't be able to use it to find all the trusts relations.
I think better solution is to separate the basic trust levels from the advanced trust relations. Like
advanced_trust(A,B,K) :- trusts(A,B,K) ; trusts(B,A,K).
Related
I am trying to implement a simple line-search algorithm in Julia. I am new to Julia programming, so I am learning it on the go. I'd like to ask for some help, if possible, to correct an error while running the code.
Source code.
using LinearAlgebra
function bracket_minimum(f, x = 0, s = 1e-2, k = 2.0)
a, fa = x, f(x)
b, fb = x + s, f(x + s)
if(fb > fa)
a, b = b, a
fa, fb = fb, fa
s = -s
end
while(true)
c, fc = b + s, f(b + s)
if(fb < fc)
return a < c ? (a, c) : (c, a)
else
a, fa, b, fb = b, fb, c, fc
s *= k
end
end
end
function bisection(f, a₀, b₀, ϵ)
function D(f,a)
# Approximate the first derivative using central differences
h = 0.001
return (f(a + h) - f(a - h))/(2 * h)
end
a = a₀
b = b₀
while((b - a) > ϵ)
c = (a + b)/2.0
if D(f,c) > 0
b = c
else
a = c
end
end
return (a,b)
end
function line_search(f::Function, x::Vector{Float64}, d::Vector{Float64})
println("Hello")
objective = α -> f(x + α*d)
a, b = bracket_minimum(objective)
α = bisection(objective, a, b, 1e-5)
return α, x + α*d
end
f(x) = sin(x[1] * x[2]) + exp(x[2] + x[3]) - x[3]
x = [1,2,3]
d = [0, -1, -1]
α, x_min = line_search(f, x, d)
I am getting a Linear algebraic error, so I think I must not be passing vectors correctly or perhaps I am not doing scalar-vector multiplication correctly. But, I was having a hard-time figuring out. If I step through the code, it fails on the function call line_search(f,x,d) and does not even enter inside the function body.
Error description.
ERROR: MethodError: no method matching *(::Tuple{Float64,Float64}, ::Array{Int64,1})
Closest candidates are:
*(::Any, ::Any, ::Any, ::Any...) at operators.jl:538
*(::Adjoint{var"#s828",var"#s8281"} where var"#s8281"<:(AbstractArray{T,1} where T) where var"#s828"<:Number, ::AbstractArray{var"#s827",1} where var"#s827"<:Number) at C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.5\LinearAlgebra\src\adjtrans.jl:283
*(::Transpose{T,var"#s828"} where var"#s828"<:(AbstractArray{T,1} where T), ::AbstractArray{T,1}) where T<:Real at C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.5\LinearAlgebra\src\adjtrans.jl:284
Here is a fix in the code (I have cleaned up several stylistic things, but the key problem that your bisection returned a tuple not a value - I have changed it to return the center of the bracketing interval):
function bracket_minimum(f, x = 0.0, s = 1e-2, k = 2.0)
a, fa = x, f(x)
b, fb = x + s, f(x + s)
if fb > fa
a, b = b, a
fa, fb = fb, fa
s = -s
end
while true
s *= k
c, fc = b + s, f(b + s)
if fb < fc
return minmax(a, c)
else
a, fa, b, fb = b, fb, c, fc
end
end
end
function bisection(f, a₀, b₀, ϵ)
function D(f, a)
# Approximate the first derivative using central differences
h = 0.001
return (f(a + h) - f(a - h)) / (2 * h)
end
a = a₀
b = b₀
while (b - a) > ϵ
c = (a + b) / 2.0
if D(f, c) > 0
b = c
else
a = c
end
end
return (a + b) / 2 # this was changed
end
function line_search(f::Function, x::Vector{Float64}, d::Vector{Float64})
#assert length(x) == length(d)
objective(α) = f(x .+ α .* d)
a, b = bracket_minimum(objective)
α = bisection(objective, a, b, 1e-5)
return α, x .+ α .* d
end
f(x) = sin(x[1] * x[2]) + exp(x[2] + x[3]) - x[3]
x = [1.0, 2.0, 3.0]
d = [0.0, -1.0, -1.0]
α, x_min = line_search(f, x, d)
I was not commenting on the algorithm, as I assume you are writing this as a programming exercise and you are not trying to write the fastest and most robust algorithm.
I've tried to reproduce the model from a PYMC3 and Stan comparison. But it seems to run slowly and when I look at #code_warntype there are some things -- K and N I think -- which the compiler seemingly calls Any.
I've tried adding types -- though I can't add types to turing_model's arguments and things are complicated within turing_model because it's using autodiff variables and not the usuals. I put all the code into the function do_it to avoid globals, because they say that globals can slow things down. (It actually seems slower, though.)
Any suggestions as to what's causing the problem? The turing_model code is what's iterating, so that should make the most difference.
using Turing, StatsPlots, Random
sigmoid(x) = 1.0 / (1.0 + exp(-x))
function scale(w0::Float64, w1::Array{Float64,1})
scale = √(w0^2 + sum(w1 .^ 2))
return w0 / scale, w1 ./ scale
end
function do_it(iterations::Int64)::Chains
K = 10 # predictor dimension
N = 1000 # number of data samples
X = rand(N, K) # predictors (1000, 10)
w1 = rand(K) # weights (10,)
w0 = -median(X * w1) # 50% of elements for each class (number)
w0, w1 = scale(w0, w1) # unit length (euclidean)
w_true = [w0, w1...]
y = (w0 .+ (X * w1)) .> 0.0 # labels
y = [Float64(x) for x in y]
σ = 5.0
σm = [x == y ? σ : 0.0 for x in 1:K, y in 1:K]
#model turing_model(X, y, σ, σm) = begin
w0_pred ~ Normal(0.0, σ)
w1_pred ~ MvNormal(σm)
p = sigmoid.(w0_pred .+ (X * w1_pred))
#inbounds for n in 1:length(y)
y[n] ~ Bernoulli(p[n])
end
end
#time chain = sample(turing_model(X, y, σ, σm), NUTS(iterations, 200, 0.65));
# ϵ = 0.5
# τ = 10
# #time chain = sample(turing_model(X, y, σ), HMC(iterations, ϵ, τ));
return (w_true=w_true, chains=chain::Chains)
end
chain = do_it(1000)
This question already has answers here:
Value of bindings in SML?
(2 answers)
Closed 6 years ago.
Could someone please help. I don't get the sequence of evaluation here and how we got values of "ans". e.g. in the first example there's no value of y and I'm not sure whether this returns a pair or calls x ! (fn y => y x). It would be very helpful if you can Trace each expression.
val x = 1
val f = (fn y => y x)
val x = 7
val g = (fn y => x - y)
val ans = f g
val ans = 6 : int
=====================================
fun f p =
let
val x = 3
val y = 4
val (z,w) = p
in
(z (w y)) + x
end
val x = 1
val y = 2
val ans = f((fn z => x + z), (fn x => x + x + 0))
val ans = 12 : int
There are a few things which help make problems like this much clearer
when trying understand an alien function Lexical scoping works.
add in types to the parameters and return values without modifying the program, the compiler will tell you if you get it wrong...
replace anonymous functions with named ones.
rename variable bindings that have the same names but refer to different lexical scope.
remove variable bindings that only get used once.
binding a value to a name does not actually perform any computation,
so is merely for the benefit of the reader, if it is not doing that job
it merely serves to obfuscate, then by all means remove it.
fun f (y1 : int -> 'a) = y1 1 : 'a;
fun g (y2 : int) = 7 - y2 : int;
val ans : int = f g;
so g is given as a parameter to f, f calls g giving it the parameter x having the value 1 making y2 = 1, which g subtracts 7 - 1 returning 6.
the return value of g is an int, thus f's 'a type when g is applied to it is an int.
for the 2nd one clean it up a bit, I pulled the anonymous fn's out into their own and named values and call f (foo, bar) to make it more readable...
fun f p =
let val x = 3
val y = 4
val (z, w) = p
in (z (w y)) + x end
fun foo z = z + 1;
fun bar x = x * 2;
val ans = f(foo, bar);
Finally, we can get rid of the let values which are only used once
and replace the (z,w) = p with just (z, w) as a parameter to the function which should be much easier to follow
fun f (z, w) = (z (w 4)) + 3
fun foo z = z + 1;
fun bar x = x * 2;
val ans = f(foo, bar);
val ans = ((4 * 2) + 1) + 3
Not sure if this is the correct place to ask a cryptography question, but here goes.
I am trying to work out "d" in RSA, I have worked out p, q, e, n and ø(n);
p = 79, q = 113, e = 2621
n = pq ø(n) = (p-1)(q-1)
n = 79 x 113 = 8927 ø(n) = 78 x 112 = 8736
e = 2621
d = ???
I cant seem to find d, I know that d is meant to be a value that.. ed mod ø(n) = 1. Any help will be appreciated
As an example would be e = 17, d = 2753, ø(n) = 3120
17 * 2753 mod 3120 = 1
You are looking for the modular inverse of e (mod n), which can be computed using the extended Euclidean algorithm:
function inverse(x, m)
a, b, u := 0, m, 1
while x > 0
q := b // x # integer division
x, a, b, u := b % x, u, x, a - q * u
if b == 1 return a % m
error "must be coprime"
Thus, in your examples, inverse(17, 3120) = 2753 and inverse(2621, 8736) = 4373. If you don't want to implement the algorithm, you can ask Wolfram|Alpha for the answer.
The algorithm you need is the Extended Euclidean Algorithm. This allows you to compute the coefficients of Bézout's identity which states that for any two non-zero integers a and b, there exist integers x and y such that:
ax + by = gcd(a,b)
This might not seem immediately useful, however we know that e and φ(n) are coprime, gcd(e,φ(n)) = 1. So the algorithm gives us x and y such that:
ex + φ(n)y = gcd(e,φ(n))
= 1
Re-arrange:
ex = -φ(n)y + 1
This is equivalent to saying ex mod φ(n) = 1, so x = d.
For example you need to get d in the next:
3*d = 1 (mod 9167368)
this is equally:
3*d = 1 + k * 9167368, where k = 1, 2, 3, ...
rewrite it:
d = (1 + k * 9167368)/3
Your d must be the integer with the lowest k.
Let's write the formula:
d = (1 + k * fi)/e
public static int MultiplicativeInverse(int e, int fi) {
double result;
int k = 1;
while (true) {
result = (1 + (k * fi)) / (double) e;
if ((Math.Round(result, 5) % 1) == 0) {
//integer
return (int)result;
} else {
k++;
}
}
}
let's test this code:
Assert.AreEqual(Helper.MultiplicativeInverse(3, 9167368), 6111579); // passed
We are supposed to write a program to solve the following initial value problem numerically using 4th order Runge-Kutta. That algorithm isn't a problem and I can post my solution when I finish.
The problem is, separating it out cleanly into something I can put into Runge-Kutta.
e^(-x') = x' −x + exp(−t^3)
x(t=0) = 1
Any ideas what type of ODE this is called? or methods to solve this? I feel more confident with CS skills and programming numerical methods than I do in math... so any insights into this problem would be helpful.
Update: If anyone is interested in the solution the code is below. I thought it was an interesting problem.
import numpy as np
import matplotlib.pyplot as plt
def Newton(fn, dfn, xp_guess, x, t, tolerance):
iterations = 0
value = 100.
max_iter = 100
xp = xp_guess
value = fn(t, x, xp)
while (abs(value) > tolerance and iterations < max_iter):
xp = xp - (value / dfn(t,x,xp))
value = fn(t,x,xp)
iterations += 1
root = xp
return root
tolerance = 0.00001
x_init = 1.
tmin = 0.0
tmax = 4.0
t = tmin
n = 1
y = 0.0
xp_init = 0.5
def fn(t,x,xp):
'''
0 = x' - x + e^(-t^3) - e^(-x')
'''
return (xp - x + np.e**(-t**3.) - np.e**(-xp))
def dfn(t,x,xp):
return 1 + np.e**(-xp)
i = 0
h = 0.0001
tarr = np.arange(tmin, tmax, h)
y = np.zeros((len(tarr)))
x = x_init
xp = xp_init
for t in tarr:
# RK4 with values coming from Newton's method
y[i] = x
f1 = Newton(fn, dfn, xp, x, t, tolerance)
K1 = h * f1
f2 = Newton(fn, dfn, f1, x+0.5*K1, t+0.5*h, tolerance)
K2 = h * f2
f3 = Newton(fn, dfn, f2, x+0.5*K2, t+0.5*h, tolerance)
K3 = h * f3
f4 = Newton(fn, dfn, f3, x+K3, t+h, tolerance)
K4 = h * f4
x = x + (K1+2.*K2+2.*K3+K4)/6.
xp = f4
i += 1
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(tarr, y)
plt.show()
For Runge-Kutta you only need a numerical solution, not an analytical one.
That is, you need to be able to write a piece of code that takes (x, t) and gives back y such that exp(-y) == y - x + exp(-t**3) to within round-off error. That code can do some sort of iterative approximation algorithm, and Runge-Kutta will be perfectly happy.
Does that help?
Wolfram Alpha says the solution will look like this.
I find that it helps to have an idea of what the answer is before I start.
It also helps to know that a resource like Wolfram Alpha is available to you at all times.
PS - What does it mean to be a student or professor in a time of Internet, Wolfram Alpha, Google, Wikipedia, etc.?
Writing K for x - exp( -t^3), we want to solve exp(-y) = y - K; I get y = K + W(exp(-K)) where W is Lambert's W function, eg here